很简单,几行代码就能实现
public static void main(String[] args) {
try {
// 读取txt文件内容
BufferedReader reader = new BufferedReader(new FileReader("D:\\dep.txt"));
String content = "";
String line = reader.readLine();
while (line != null) {
content += line;
line = reader.readLine();
}
reader.close();
// 转成对象
JSONObject w =JSONObject.parseObject(content);
//对象中取数组,下面就可以进行操作
JSONArray deptList = w.getJSONArray("data");
// 输出数组
} catch (Exception e) {
e.printStackTrace();
}
}
给小白解释下
通过BufferedReader和FileReader来读取文本文件的内容。BufferedReader用于逐行读取文件内容,FileReader用于将文件内容转换为字符流。
声明一个String类型的变量content,用于存储文件的内容。
使用reader.readLine()方法来逐行读取文件内容,将每行的内容追加到content变量中。
当读取到文件末尾时,reader.readLine()方法会返回null,表示文件读取结束,此时退出循环。
关闭BufferedReader,释放资源。
在catch块中,如果发生异常,将异常信息打印到控制台。
这段代码实际上只是读取了文本文件的内容,并将内容存储在content变量中,但并没有输出数组。如果你想要输出数组,你需要对content进行进一步处理,例如将文本内容转换为数组,然后输出。
注意,json文件最好使用在线json压缩工具给压缩一下,不然读出来的数据有空格