I am attempting to make a multiThread downloader in java. It works but the file that I download is always missing some bytes.
I have searched and found many example of multiThreaded web crawlers but nothing simple, so can anyone tell me if my method could work?
I don't know if the problem is with ordering the bytes.
I have tried BlockingQueue but it did not work
URL url = new URL(mURL);
final HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.connect();
final BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
final File f = new File("tr.exe");
if (f.exists()) {
f.delete();
}
// open the output file and seek to the start location
Thread t1 = new Thread() {
public void run() {
try {
RandomAccessFile raf = new RandomAccessFile(f, "rw");
raf.seek(0);
int numRead;
int mStartByte = 0;
byte data[] = new byte[conn.getContentLength() / 2];
while (((numRead = in.read(data, 0, 1024)) != -1) && (mStartByte < conn.getContentLength() / 2)) {
// write to buffer
raf.write(data, 0, numRead);
// increase the startByte for resume later
mStartByte += numRead;
// increase the downloaded size
}
raf.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(MyDownloader.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MyDownloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
Thread t2 = new Thread() {
public void run() {
try {
RandomAccessFile raf = new RandomAccessFile(f, "rw");
raf.seek(conn.getContentLengthLong() / 2);
int numRead;
int mStartByte = conn.getContentLength() / 2;
byte data[] = new byte[conn.getContentLength() / 2];
while (((numRead = in.read(data, 0, 1024)) != -1) && (mStartByte < conn.getContentLength())) {
// write to buffer
raf.write(data, 0, numRead);
// increase the startByte for resume later
mStartByte += numRead;
// increase the downloaded size
}
raf.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(MyDownloader.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MyDownloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
t1.start();
t2.start();