Java怎么实现读取项目中的文件
作者:NorthPath
时间:2023-04-29
来源:互联网
浏览:0
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
作者最新文章
贵州省住建厅与贝壳集团签署旅居战略合作:五大维度落地方案解析
2026-09-08 18:13
上海链家安住APP:业主主动卖房功能与成交数据解析
2026-09-08 18:11
如何批量将PPT转成PDF格式?PPT转PDF工具怎么选?
2026-09-04 16:03
PDF文件怎么压缩?3个小技巧帮你减小体积
2026-09-03 18:03
小批量试产总结报告:新产品量产导入评审实战指南
2026-09-02 19:48
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















