Mega Code Archive

 
Categories / Java / Network Protocol
 

Save binary file from web

import java.io.FileOutputStream; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class MainClass {   public static void main(String args[]) {     try {       URL root = new URL("http://");       saveBinaryFile(root);     } catch (MalformedURLException e) {       System.err.println("not URL I understand.");     }   }   public static void saveBinaryFile(URL u) {     int bufferLength = 128;     try {       URLConnection uc = u.openConnection();       String ct = uc.getContentType();       int contentLength = uc.getContentLength();       if (ct.startsWith("text/") || contentLength == -1) {         System.err.println("This is not a binary file.");         return;       }       InputStream stream = uc.getInputStream();       byte[] buffer = new byte[contentLength];       int bytesread = 0;       int offset = 0;       while (bytesread >= 0) {         bytesread = stream.read(buffer, offset, bufferLength);         if (bytesread == -1)           break;         offset += bytesread;       }       if (offset != contentLength) {         System.err.println("Error: Only read " + offset + " bytes");         System.err.println("Expected " + contentLength + " bytes");       }       String theFile = u.getFile();       theFile = theFile.substring(theFile.lastIndexOf('/') + 1);       FileOutputStream fout = new FileOutputStream(theFile);       fout.write(buffer);     } catch (Exception e) {       System.err.println(e);     }     return;   } }