如何使用Java在浏览器中启动文件下载



我正在创建一个简单的应用程序,用于向服务器上传文件和从服务器下载文件。

出于测试目的,我使用localhost进行测试。我正在寻找一种从Java浏览器下载文件的简单方法。

这里有一个用Java从网站下载文件的代码。。。你可以调整这个

    import java.io.BufferedInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;

    public class DownloadFile {
      public static void main(String[] args) throws IOException {
             String fileName = "fileName.txt"; 
             URL link = new URL("http://websiteToDownloadFrom.com");
             InputStream in = new BufferedInputStream(link.openStream());
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             byte[] buf = new byte[1024];
             int n = 0;
             while (-1!=(n=in.read(buf)))
             {
                out.write(buf, 0, n);
             }
             out.close();
             in.close();
             byte[] response = out.toByteArray();
             FileOutputStream fos = new FileOutputStream(fileName);
             fos.write(response);
             fos.close();
    }
}

如果在localhost:中

url = new URL("http://localhost:8052/directoryPath/fileName.pdf");

最新更新