I am looking for some confirmation that FileOutputStream works like I think it does. I am downloading a file and, if I lose the network connection, trying to resume the download from where it left off.
How I am trying to do this is to open the FileOutputStream as not appending and then writing nothing at an offset. My question is will that work or does opening it as non appending delete the contents? Also if I write at an offset will it continue to write after that position in the file on subsequent calls to write?
File outFile = new File(outFileName);
FileOutputStream out = new FileOutputStream(outFile);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
long fileSize = connection.getContentLength();
int status = DOWNLOADING;
connection.connect();
InputStream in = connection.getInputStream();
long downloaded = in.skip(outFile.length());
publishProgress(downloaded, fileSize);
try
{
int read = 0;
byte buffer[] = new byte[MAX_BUFFER_SIZE];
// Skip ahead in the out buffer
out.write(buffer, (int)downloaded, read);
while(status == DOWNLOADING)
{
if(!NetworkUtils.isConnected(_context))
{
// This breaks us out of the doInBackground in the AsyncTask
_downloadFailed = true;
throw new Exception("Network Connectivity Lost!");
}
read = in.read(buffer);
if(read == -1)
{
publishProgress(fileSize);
break;
}
out.write(buffer, 0, read);
downloaded += read;
publishProgress(downloaded);
}
}
finally
{
out.close();
in.close();
connection.disconnect();
}
You should also take a look at the RandomAccessFile class, which will let you seek to a certain position and start writing from there without truncating the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With