繁体   English   中英

使用 Java 下载并保存文件

[英]Download and save a file using Java

假设我有一个 URL,比如 something.domain/myfile.txt 然后我想用“保存文件”对话框保存这个文件。

我已尽力做到这一点,但每次我使用对话框保存文件时,该文件都不存在。

一个例子或我可以找到这方面信息的地方会很有帮助!

        URL website = null;
                try {
                    website = new URL(<insert url here>);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                ReadableByteChannel rbc = null;
                try {
                    rbc = Channels.newChannel(website.openStream());
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(new File("minecraft.jar"));
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
                try {
                    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                    JFileChooser fileChooser = new JFileChooser();
                    if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
                      File dir = fileChooser.getCurrentDirectory(); 
                      dir.mkdir();
                      //After this point is where I need help.

我相信这就是您要寻找的:

if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION)
{
  File file = fileChooser.getSelectedFile();
  // whatever you want to do with the file
  System.out.println("The file is "+file.getAbsolutePath());
  // fos = new FileOutputStream(file) ...
}

您是否注意到在您的代码中,您在为用户提供选择目的地的选项之前尝试保存/下载文件?

我会将代码拆分为三个不同的操作:

  1. 一种负责将字节从InputStream (网络)传输到OutputStream (文件)的方法。
  2. 一种向用户显示对话框的方法,以便他可以选择存储文件的位置。
  3. 完成整个任务的方法:选择一个文件并将字节从网络传输到它。

1)会是这样的(你不需要使用 NIO API 来实现它):

public void transfer(InputStream in, OutputStream out) throws IOException {
   byte[] buffer = new byte[2048];
   int bytesRead;
   while ((bytesRead = in.read(buffer)) > 0) {
      out.write(buffer, 0, bytesRead);
   }
}

2)与杜克林已经说过的非常相似:

public File chooseFile() {
  File result = null;
  JFileChooser fileChooser = new JFileChooser();
  if (fileChooser.showSaveDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
    result = fileChooser.getSelectedFile();
  }
  return result;
}

3) 那么,将这两个操作结合起来真的很简单:

public void saveFileFromWeb(URL url) {
  File file = chooseFile();   // 1. Choose the destination file
  if (file != null) {
    // 2. Create parent folder structure
    File folder = file.getParentFile();
    if (!folder.exist()) {
       folder.mkdirs();
    }

    InputStream in = null;
    OutputStream out = null;
    try {
      // 3. Initialise streams
      in = url.openStream();
      out = new FileOuputStream(file);
      // 4. Transfer data
      transfer(in, out);
    } catch (IOException e) {
       e.printStackTrace();
    } finally {
      // 5. close streams
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) { /* ignore */ }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) { /* ignore */ }
    }
  }
}

注意:1) 和 2) 可能是私有方法。 当然,您可以只执行一个操作,但拆分它可以让您大致了解要执行的不同步骤。

注2 :我简化了异常处理部分

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM