在 java 中使用 JSON 读写字符串文件

Reading and writing String files with JSON in java

我想读取一个文本文件并对其进行处理 data.so 例如,输入文件如下所示:

john,judd,134
Kaufman,kim,345

然后程序应该以 JSON 文件的形式解析和存储这些数据,以便进一步组织这些数据 processing.I' 使用 JSON-simple 完成此任务。这是我写的原型代码:

package com.company;

import org.json.simple.JSONObject;

import java.io.*;

public class Main {


static JSONObject jsonObject = new JSONObject();
static String output;

public static void main(String[] args) throws IOException {

    read("/Users/Sepehr/Desktop/JSONexample.txt");
    write("/Users/Sepehr/Desktop/JSONexampleout,txt");

}

public static String read(String filenameIn) throws IOException {

    BufferedReader bufferedReader = new BufferedReader(new FileReader(filenameIn));
    String s ;

    while ( (s = bufferedReader.readLine() ) != null)

    {
        String[] stringsArr = s.split(",");


        jsonObject.put( "famname" , stringsArr[0] );
        jsonObject.put("name" , stringsArr[1]);
        jsonObject.put("id", stringsArr[2]);

        bufferedReader.close();


    }

    return output=jsonObject.toJSONString();


}


public static String write(String filenameOut) throws FileNotFoundException {

    PrintWriter printWriter = new PrintWriter(filenameOut);
    printWriter.write(jsonObject.toJSONString());
    printWriter.close();

    String se = "yaaayyy :|";
    return se;

}



}

在 运行 程序之后,这些是我得到的异常:

Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(BufferedReader.java:97)
at java.io.BufferedReader.readLine(BufferedReader.java:292)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at com.company.Main.read(Main.java:30)
at com.company.Main.main(Main.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

到底出了什么问题?

这个程序应该如何做更好的设计?

您正在关闭循环中的 BufferedReader

while ( (s = bufferedReader.readLine() ) != null)

    {
        String[] stringsArr = s.split(",");


        jsonObject.put( "famname" , stringsArr[0] );
        jsonObject.put("name" , stringsArr[1]);
        jsonObject.put("id", stringsArr[2]);

        //*************
        bufferedReader.close(); // don't close the reader!
        //*************

    }