Save binary file from web : Web Server Client « Network Protocol « Java






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;
  }
}

           
       








Related examples in the same category

1.Java HTTP/HTTPS Server Based on new io
2.Connect with a Web serverConnect with a Web server
3.Reading URLs Protected with HTTP Authentication
4.Reading Web Pages with StreamsReading Web Pages with Streams
5.Reading Web Pages, with Socket ChannelsReading Web Pages, with Socket Channels
6.Reading Web Pages with Nonblocking ChannelsReading Web Pages with Nonblocking Channels
7.A Simple Web ServerA Simple Web Server
8.Web server