我想讀的文本文件並處理它data.so例如輸入文件看起來像:讀取和寫入字符串的文件用JSON在Java中
john,judd,134
Kaufman,kim,345
則程序應該解析和存儲這些數據在JSON文件的形式,從而將進一步processing.I'm使用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)
究竟是什麼錯誤?
以及如何爲這個程序做出更好的設計?
在一個側面說明,別忘了在固定的輸出文件擴展名的錯字(點而不是逗號)'寫(「/用戶/ 'JSONexampleout.txt'不是'JSONexampleout,txt' – mshaaban 2015-04-01 09:39:50