Here is thread code of my java project, I want to make multiple download processes with threadpool, but I got java.lang.Negat iveArraySizeExc eption error.Why is this so?
Thanks for any reply.
Code:
public void run() {
InputStream stream = null;
File file=new File(url);
RandomAccessFile rfile=null;
System.out.println("Download started: "+id);
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
int contentLength = connection.getContentLength();
System.out.println(contentLength);
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
}
// Open file and seek to the end of it.
rfile=file.openRandomAccessFile(url);
rfile.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1){
System.out.println(buffer);
System.out.println(file.getFileName()+" was downloaded");
break;
}
// Write buffer to file.
rfile.write(buffer, 0, read);
downloaded += read;
}
//Thread.sleep(1000);
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
}
} catch (Exception e) {
System.out.println("There is an Error!"+e);
}
Comment