Last active
September 22, 2016 06:09
-
-
Save sks147/b75968de099515bfbcabfe9936aa98a2 to your computer and use it in GitHub Desktop.
Determine the Server Side MIME type information and Spawn an external viewer to display the file.
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; | |
//Determine the Server Side MIME type information and Spawn an external viewer to display the file. | |
public class URLDownloader{ | |
public static void main (String[] args){ | |
URL u = null; | |
File f = null; | |
try{ | |
u = new URL("http://www.bbc.co.uk/accessibility/guides/"); | |
HttpURLConnection http = (HttpURLConnection) u.openConnection(); | |
//get MIME type of the http connection | |
String MIMEtype = http.getContentType(); | |
System.out.println("MIME type of the content : "+MIMEtype); | |
//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 | |
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(); | |
//opening the downloaded file using default app based on the content-type | |
System.out.println("Opening the downloaded file...\n"); | |
if(f.exists()){ | |
Desktop.getDesktop().open(f); | |
}else{ | |
System.out.println("File not available"); | |
} | |
}catch (MalformedURLException ex){ | |
System.err.println(ex); | |
}catch (IOException ex){ | |
System.err.println(ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment