import java.net.*;
import java.io.*;
public class saveBinaryFile {
public static void main (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
} // end main
public static void saveBinaryFile(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;
} // end saveBinaryFile
}
|