[英]How to initiate a file download in the browser using Java?
I am creating a simple application thats uploads and downloads files to/from a server. 我正在创建一个简单的应用程序,可以将文件上传到服务器或从服务器下载文件。
For testing purposes I am using localhost
for testing. 出于测试目的,我使用localhost
进行测试。 I am looking for a simple way to download a file from the browser in Java. 我正在寻找一种简单的方法来从Java浏览器中下载文件。
Here is a code to download files from a web site in Java ... You can adapt this 这是从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();
}
}
If it is in localhost: 如果在本地主机中:
url = new URL("http://localhost:8052/directoryPath/fileName.pdf");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.