Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What 's wrong with it?? Thanx!  RSS feed

 
Javan Li
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.net.*;
import java.io.*;
public class BinarySaver {
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.");
}
catch (IOException e) {
System.err.println(e);
e.printStackTrace();
}
} // end for
} // end main

public static void saveBinaryFile(URL u) throws IOException {

URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
System.out.println(contentType);//1
int contentLength = uc.getContentLength();
System.out.println(contentLength);
if (contentType.startsWith("text/") || contentLength == -1 ) {
throw new IOException("This is not a binary file.");
}
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);

int bytesRead = 0;
int offset = 0;
System.out.println(contentType);//2
String filename = u.getFile();
filename = filename.substring(filename.lastIndexOf('/') + 1);
FileOutputStream fout = new FileOutputStream(filename);


while (offset < contentLength) {
byte[] data = new byte[1024];
if((contentLength-offset)>data.length){
System.out.println("Offset "+offset);
bytesRead = in.read(data, offset, data.length);
}else{
System.out.println("Offset "+offset);
bytesRead = in.read(data, offset, contentLength-offset);
}
if (bytesRead == -1) break;
fout.write(data);
offset += bytesRead;
}

in.close();
fout.flush();
fout.close();

}
} // end BinarySaver

OUTPUT:
--------------------Configuration: J2SE <Default>--------------------
image/gif
1934
image/gif
Offset 0
Offset 1024
java.lang.IndexOutOfBoundsException
at java.io.BufferedInputStream.read(BufferedInputStream.java:275)
at BinarySaver.saveBinaryFile(BinarySaver.java:56)
at BinarySaver.main(BinarySaver.java:12)
Exception in thread "main"
Process completed.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by li jia:
You're trying to read into the data array, offset 1024, which is beyond the end of the array.
- Peter
 
Javan Li
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!