Last active
September 22, 2016 05:51
-
-
Save sks147/849db2f7c09255c52b73142e27f868d0 to your computer and use it in GitHub Desktop.
Read all data from the http connection and write it to a temporary file created on your local system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.lang.*; | |
import java.io.*; | |
import java.net.*; | |
import java.awt.Desktop; | |
// Read all data from the http connection and write it to a temporary | |
// file created on your local system | |
public class HTTPConnectionReader{ | |
public static void main (String[] args){ | |
URL u = null; | |
try{ | |
u = new URL("http://www.bbc.co.uk/accessibility/guides/"); | |
HttpURLConnection http = (HttpURLConnection) u.openConnection(); | |
//read by input stream | |
InputStream raw = http.getInputStream(); | |
//procedure to download a file | |
String filename = "output.html"; | |
String savedir = "/Users/Sumit/Desktop/"; | |
String saveFilePath = savedir +"/"+ filename; | |
//create a new file | |
File f = new File(saveFilePath); | |
//open the File output stream on the file | |
FileOutputStream out = new FileOutputStream(saveFilePath); | |
//get the number of bytes available to read | |
int bytesAvailable = raw.available(); | |
//create a buffer input byte array | |
byte[] input = new byte[bytesAvailable]; | |
int bytesRead = bytesAvailable; | |
while((bytesRead = raw.read(input)) != -1){ | |
out.write(input, 0, bytesRead); | |
} | |
//close the streams | |
out.close(); | |
raw.close(); | |
}catch (MalformedURLException ex){ | |
System.err.println(ex); | |
}catch (IOException ex){ | |
System.err.println(ex); | |
} | |
System.out.println("File output.html has been saved on Desktop"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment