Java怎么实现读取项目中的文件
作者:NorthPath
时间:2023-05-03
浏览:3
1.读取jsonfile1.1Jsondependencycom.alibabafastjson1.2.761.2字节流重点部分./代表同级目录…/代表上级目录(两个点)/代表根目录publicclassFileService{publicJSONObjectreader(){JSONObjectresultJson=null;Stringfile="src/main/resources/config_dev.json";InputStreamis=null;try{is=newFileIn
本文目录
1. 读取json file
1.1 Json dependency
com.alibaba fastjson 1.2.76
1.2 字节流
重点部分
. /代表同级目录
…/ 代表上级目录(两个点)
/ 代表根目录
public class FileService {
public JSONObject reader(){
JSONObject resultJson = null;
String file = "src/main/resources/config_dev.json";
InputStream is = null;
try {
is = new FileInputStream(file);//操作
byte[] bytes = new byte[5000];//数组容量超级大,一次能将中英混合文本全部读取完
int len = -1;
while ((len = is.read(bytes)) != -1) {
String str = new String(bytes, 0, len, "UTF-8");
resultJson = process(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {//释放资源
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultJson;
}
private static JSONObject process(String content) {
JSONObject json = JSONObject.parseObject(content);
return json;
}
}1.3 buffer reader
public static String reader(String filePath) {
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = bufferedReader.readLine();
while (lineTxt != null) {
return lineTxt;
}
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
System.out.println("Cannot find the file specified!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error reading file content!");
e.printStackTrace();
}
return null;
}2. 读取properties file
public void readPropertiesFile() {
Properties pro = new Properties();
InputStream is = this.getClass().getResourceAsStream("/application.properties");
try {
pro.load(is);
Enumeration en = pro.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = pro.getProperty(key);
System.out.println(key + "--" + value);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}3. 好看的css样式
Title Click Style
作者最新文章
如何通过EMRAI助手查询EMR组件相关问题
2026-11-01 16:16
EndNote Windows版官方下载与安装教程:许可确认到Word插件验证
2026-10-30 09:21
WinRAR压缩文件教程:参数设置与分卷压缩技巧
2026-10-29 09:38
华硕5070显卡提升AI创作效率
2026-10-27 11:04
navicat怎么设置自增主键及具体操作步骤
2026-10-22 22:43
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































