【问题标题】:File can not read correctly文件无法正确读取
【发布时间】:2015-09-04 10:51:22
【问题描述】:

我试图从 dbpedia 读取一个 json 文件并对其进行解析。但是我编写的代码无法正确读取整个 json 文件,因此出现解析错误。这是我的阅读和解析代码...

URL url=new URL("http://dbpedia.org/data3/assembly.json");

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine="asdf";
while (( in.readLine()) != null)
{
    if (inputLine=="asdf")
        inputLine=in.readLine();
    else
        inputLine+=in.readLine();
    //System.out.println(inputLine);
}
System.out.println(inputLine);
Object obj = parser.parse(inputLine);    

JSONObject jsonObject = (JSONObject) obj;

【问题讨论】:

  • 错误信息是什么?
  • 使用String.equals比较字符串
  • error msg is like this Error: Parse error on line 1: .../ontology/assembly" : { "w3.o --------------- --------^ 期待'EOF','}',',',']',得到':'实际上我与实际的json文件和“inputLine”变量的输出进行比较,它并不完整一样。
  • 旁注:考虑使用 try-with-resources 正确关闭您的流。
  • 旁注:避免在循环中连接字符串。使用 StringBuilder。

标签: java json filereader


【解决方案1】:

您可以创建一个辅助方法来从 url 读取文件:

private static String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1) {
                buffer.append(chars, 0, read); 
            }
            return buffer.toString();
        } finally {
            if (reader != null)
                reader.close();
        }
    }

那么你可以像这样调用方法

try {
    JSONObject json = new JSONObject(readUrl("http://dbpedia.org/data3/assembly.json"));
    ...

} catch (JSONException e) {
    e.printStackTrace();
}

是否需要 StringBuffer 或 StringBuilder 由您决定

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 2019-03-30
    • 2018-07-24
    • 2020-03-11
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多