使用Java将大型JSON文件下载到本地文件

时间:2012-03-19 23:18:57

标签: java json

我正在尝试从以下网址http://api.crunchbase.com/v/1/companies.js - 下载JSON到本地文件。我正在使用Java 1.7和以下JSON库 - http://www.json.org/java/ - 来尝试使其工作。

这是我的代码:

public static void download(String address, String localFileName) {
            OutputStream out = null;
            URLConnection conn = null;
            InputStream  in = null;
            try {
                    URL url = new URL(address);
                    out = new BufferedOutputStream(
                            new FileOutputStream(localFileName));
                    conn = url.openConnection();
                    in = conn.getInputStream();
                    byte[] buffer = new byte[1024];
                    int numRead;
                    long numWritten = 0;
                    while ((numRead = in.read(buffer)) != -1)
                    {
                            out.write(buffer, 0, numRead);
                            numWritten += numRead;
                            System.out.println(buffer.length);
                            System.out.println(" " + buffer.hashCode());
                    }
                   System.out.println(localFileName + "\t" + numWritten);
            } catch (Exception exception) {
                    exception.printStackTrace();
            } finally {
                    try {
                            if (in != null) {
                                    in.close();
                            }
                            if (out != null) {
                                    out.close();
                            }
                    } catch (IOException ioe) {
                    }
            }
    }

当我运行代码时,一切似乎都工作,直到循环中途程序似乎停止并且不继续读取JSON对象。

有谁知道为什么会停止阅读?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

试试这个:

public void saveUrl(String filename, String urlString) throws MalformedURLException, IOException
    {
        BufferedInputStream in = null;
        FileOutputStream fout = null;
        try
        {
                in = new BufferedInputStream(new URL(urlString).openStream());
                fout = new FileOutputStream(filename);

                byte data[] = new byte[1024];
                int count;
                while ((count = in.read(data, 0, 1024)) != -1)
                {
                        fout.write(data, 0, count);
                }
        }
        finally
        {
                if (in != null)
                        in.close();
                if (fout != null)
                        fout.close();
        }
    }

答案 1 :(得分:0)

  

有谁知道为什么会停止阅读?我该如何解决这个问题?

我看不出客户端代码明显错误。在客户端没有任何其他证据的情况下,我会查看服务器端日志,看看是否有任何线索。

IMO,最可能的解释是以下之一:

  • 服务器端代码中存在一个生成JSON的错误,它在中途崩溃。

  • 服务器(或代理/反向代理)在交互的某些部分允许的时间内超时,并且此特定请求花费的时间太长。