FileDocCategorySizeDatePackage
saveBinaryFile.javaAPI DocExample1490Thu Apr 03 15:26:48 BST 1997None

saveBinaryFile

public class saveBinaryFile extends Object

Fields Summary
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)


    for (int i = 0; i < args.length; i++) {

      try {
        URL root = new URL(args[i]);
        saveBinaryFile(root);
      }
      catch (MalformedURLException e) {
        System.err.println(args[i] + " is not URL I understand.");
      }
    } // end for

  
public static voidsaveBinaryFile(java.net.URL u)

  
    int bfr = 128;
    
    try {
      URLConnection uc = u.openConnection();
      String ct = uc.getContentType();
      int cl = uc.getContentLength();
      if (ct.startsWith("text/") || cl == -1 ) {
        System.err.println("This is not a binary file.");
        return;
      }

      InputStream theImage = uc.getInputStream();
      byte[] b = new byte[cl];
      int bytesread = 0;
      int offset = 0;
      while (bytesread >= 0) {
         bytesread = theImage.read(b, offset, bfr);
         if (bytesread == -1) break;
         offset += bytesread;
      }
      if (offset != cl) {
        System.err.println("Error: Only read " + offset + " bytes");
        System.err.println("Expected " + cl + " bytes");
      }

      String theFile = u.getFile();
      theFile = theFile.substring(theFile.lastIndexOf('/") + 1);
      FileOutputStream fout = new FileOutputStream(theFile);
      fout.write(b);
    }  // end try
    catch (Exception e) {
     System.err.println(e);
    }
    
    return;