Speed up development with full-stack environments for every branch.

Learn More

Download a file from the web [Java, Files and save]

Forked from Basic Java Example.

7259 Runs 68002 Views 31325 Copies

Code to download a file from the web

Saved

Saved

thatguyandrew1992 2

thatguyandrew1992
published 3 years ago

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 = "file.txt"; //The file that will be saved on your computer
		 URL link = new URL("http://shayconcepts.com"); //The file that you want to download
		
     //Code to download
		 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();
     //End download code
		 
		 System.out.println("Finished");

	}

}
 

Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).