如下图,读取相同目录下的txt文件

public class TestHelper {
public static JSONObject readTXT() {
JSONObject obj = new JSONObject();
String path = new TestHelper().getPath() + "test.txt";
path = path.replace("file:/", "");
path = path.replace("/", "//");
File file = new File(path);
StringBuilder sb = new StringBuilder("");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String l = null;
while ((l = br.readLine()) != null) {
sb = sb.append(l);
}
String str = sb.toString();
// System.out.println(str);
obj = JSONObject.parseObject(str);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
private String getPath(){
return TestHelper.class.getResource("").toString();
}
本文介绍了一个使用Java实现的方法,该方法可以读取当前目录下的TXT文件,并将其内容解析为JSON对象返回。通过BufferedReader逐行读取文件内容并拼接成字符串,最后利用JSON解析库将字符串转换为JSON对象。
434

被折叠的 条评论
为什么被折叠?



