代码之家  ›  专栏  ›  技术社区  ›  Daniel Vaughn

如何使用约300 MB的json文本读取url

  •  0
  • Daniel Vaughn  · 技术社区  · 3 年前

    我正试着阅读来自 https://mtgjson.com/api/v5/AllPrintings.json 。我已尝试使用此代码:

    url = new URL("https://mtgjson.com/api/v5/AllPrintings.json");
    conn = (HttpsURLConnection) url.openConnection();
    
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // error here
    
    String inputLine;
    StringBuffer content = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        content.append(inputLine);
    }
    System.out.println(content);
    

    我一直使用BufferedReader(conn.getInputStream())获取IOException。url中的文本不包含换行符。如何读取这些数据?

    编辑
    我使用的是Java 1.8和Apache NetBeans 16。我坚持使用1.8,所以我也可以使用Eclipse Neon3。

    错误

    java.io.IOException: Server returned HTTP response code: 403 for URL: https://mtgjson.com/api/v5/AllPrintings.json
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
        at tests.MtgJson.main(MtgJson.java:44)
    

    我也一直在尝试使用curl的ProcessBuilder,它给出了更好的结果,但大约一分钟后curl就停止了。如果我终止了Netbeans内部的程序,但并不总是完成文件内容的创建,那么Curl就会继续。我不应该为了curl的继续而停止我的程序。我是不是缺少什么东西让curl去上班?

    String command = "curl --keepalive-time 5 https://mtgjson.com/api/v5/AllPrintings.json";
    ProcessBuilder pb = new ProcessBuilder(command.split(" "));
    pb.redirectOutput(new File("AllPrintings.json"));
    Process process = pb.start();
    // use while() or process.waitfor();
    while(process.isAlive())
        Thread.sleep(1000);
    process.destroy();
    

    答案(因为我不能发布):

    String command = "curl https://mtgjson.com/api/v5/AllPrintings.json";
    ProcessBuilder pb = new ProcessBuilder(command.split(" "));
    
    pb.inheritIO(); // keep the program from hanging
    pb.redirectOutput(new File("AllPrintings.json"));
    
    Process process = pb.start();
    process.waitFor(); // waiting for the process to terminate.
    

    完整的文件在不挂起的情况下创建,然后程序将关闭。Curl将信息输出到控制台,并且必须被消耗 (found here) .

    0 回复  |  直到 3 年前
        1
  •  0
  •   DuncG    3 年前

    不需要使用字节->字符转换 BufferedReader 只是为了复制。相反,使用Java NIO将内容直接复制到文件中 Files.copy ,然后使用输出文件进行任何进一步处理:

    Path file = Path.of("big.json"); 
    // Older JDK use Paths.get("filename")
    Files.copy(conn.getInputStream(), file);
    System.out.println("Saved "+Files.size(file)+" bytes to "+file);
    

    应打印:

    Saved 313144388 bytes to big.json
    
    推荐文章