文件无法正确读取

时间:2015-09-04 10:51:23

标签: java json filereader

我试图从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;

1 个答案:

答案 0 :(得分:2)

您可以创建一个帮助方法来从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

,这取决于您