I am creating a simple application thats uploads and downloads files to/from a server.
For testing purposes I am using localhost
for testing. I am looking for a simple way to download a file from the browser in Java.
Here is a code to download files from a web site in Java ... You can adapt this
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.