问题
i want to download a videofile from the web. It is 121 MB. Now i want to pre allocate this 121 MB on the disk (with zeros or what ever) and fill it step by step with the data of the inputstream from the urlconnection. Or with other words: It doesn't matter how much has been downloaded yet - the file size is always the destinated 121MB.
Is it possible? thank you
回答1:
i got the solution. First of all i write the empty dummy file and then i reopen the empty file and replace the bytes:
System.out.println("Writing dummy ...");
byte buf[] = new byte[1024];
for (int size = 0; size < fileLength; size += buf.length) {
out.write(buf);
out.flush();
}
out.close();
System.out.println("Writing data ...");
RandomAccessFile raf = new RandomAccessFile(temp, "rw");
int count = 0;
long total = 0;
while ((count = stream.read(buf)) > 0) {
raf.seek(total);
raf.write(buf);
total += count;
}
raf.close();
回答2:
Obviously. Create file, write loop that writes 121*1024*1024 bytes to this file. You can either write byte-by-byte or using chunks. Chunks are preferable from performance perspective.
Here is the demo code:
byte[] bytes = new byte[1024]; // 1KB array.
OutputStream os = new FileOutputStream(myFilePath);
for (int size = 0; size < 121*1024*1024; size += bytes.length;) {
os.write(b);
os.flush();
}
os.close();
来源:https://stackoverflow.com/questions/16588142/java-fill-preallocated-file-with-data-on-drive