【问题标题】:Get Internet file and make it to File object using Java? [duplicate]获取 Internet 文件并使用 Java 将其转换为 File 对象? [复制]
【发布时间】:2023-04-06 23:11:01
【问题描述】:

可能重复:
Reading binary file from URLConnection

现在我有一个网址:

(例如http://elsa.berkeley.edu/~saez/TabFig2005prel.xls,使用 http: 方案)。

我需要访问该文件并将其作为文件对象存储在我的程序中,以便我可以完成以下工作。所以有人知道如何将它变成一个 File 对象吗?我不知道如何将 InputStream 转换为文件。

谢谢 艾伦

【问题讨论】:

标签: java file url io inputstream


【解决方案1】:
URL url = new URL("http://elsa.berkeley.edu/~saez/TabFig2005prel.xls");
InputStream in = url.openStream();
try {
    OutputStream out = new FileOutputStream("output.xls");
    try {
        byte buf[] = new byte[4096];
        for (int n = in.read(buf); n > 0; n = in.read(buf)) {
            out.write(buf, 0, n);
        }
    } finally {
        out.close();
    }
} finally {
    in.close();
}

【讨论】:

    【解决方案2】:

    可以使用如下代码(假设InputStream对象名称为“content”)

    File myFile = new File("newFile.ext");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myFile);
        int read = 0;
        byte[] buff = new byte[1024];
        while ((read = content.read(buff)) > -1)
            fos.write(buff, 0, read);
    } catch (IOException e1) {
        /* do something? */
    } finally {
        if (fos != null) {
            try { fos.close() } catch (IOException e2) {/* do something? */}
        }
    }
    

    【讨论】:

      【解决方案3】:
      int chunkSize = 500;
      
          BufferedInputStream in = new java.io.BufferedInputStream(new URL("http://javakata6425.appspot.com/db_imgs/projectsBinaries/photoLib/photoLib.jar").openStream());
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d://temp//photoLib.jar"), chunkSize);
          byte[] data = new byte[chunkSize];
          int x = 0;
          while ((x = in.read(data, 0, chunkSize)) >= 0) {
              out.write(data, 0, x);
          }
          out.close();
          in.close();
      

      【讨论】:

        【解决方案4】:

        如何使用 apache commons-io (http://commons.apache.org/io/)

        它有一个

        FileUtils.copyURLToFile(URL,File);
        

        【讨论】:

          【解决方案5】:

          伪代码:

          create FileWriter pointing to "localdrive/local_copy.xls"
          foreach byte you can read from the input stream:
              write the byte to the filewriter
          flush the filewriter
          close the filewriter
          

          瞧。您现在已将文件保存在本地。

          【讨论】:

            猜你喜欢
            • 2012-09-15
            • 1970-01-01
            • 2021-06-02
            • 2013-03-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-09-10
            相关资源
            最近更新 更多