我正在寻找 FileOutputStream
是否像我认为的那样工作的确认。我正在下载一个文件,如果我失去了网络连接,我会尝试从中断的地方继续下载。
我尝试这样做的方式是打开 FileOutputStream,而不是附加,然后在偏移量处不写入任何内容。我的问题是这会起作用还是以非附加方式打开它会删除内容?另外,如果我在一个偏移量处写入,它会在后续调用写入时继续在文件中的该位置之后写入吗?
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();
}
最佳答案
您还应该看看 RandomAccessFile
类,它可以让您定位到某个位置并从那里开始写入,而不会截断文件。
关于java - FileOutputStream 头指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5821767/