我想一块一块地读一个文件。该文件被分成几个部分,存储在不同类型的媒体上。我目前所做的是调用文件的每个单独部分,然后将其合并回原始文件。
问题是我需要等到所有块都到达才能播放/打开文件。是否有可能在他们到达时阅读这些块,而不是等待它们全部到达。
我正在处理媒体文件(电影文件)。
你想要的是source data line。这非常适合当您的数据太大而无法立即将其保存在内存中时,因此您可以在收到整个文件之前开始播放它。或者如果文件永远不会结束。
http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read
我会使用这个FileInputStream
请参阅InputSteram.read(byte[])一次读取字节数。
示例代码:
try {
File file = new File("myFile");
FileInputStream is = new FileInputStream(file);
byte[] chunk = new byte[1024];
int chunkLen = 0;
while ((chunkLen = is.read(chunk)) != -1) {
// your code..
}
} catch (FileNotFoundException fnfE) {
// file not found, handle case
} catch (IOException ioE) {
// problem reading, handle case
}
而不是旧的io,您可以尝试使用nio来读取内存中的块而不是完整文件。您可以使用Channel从多个源获取数据
RandomAccessFile aFile = new RandomAccessFile(
"test.txt","r");
FileChannel inChannel = aFile.getChannel();
long fileSize = inChannel.size();
ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
inChannel.read(buffer);
//buffer.rewind();
buffer.flip();
for (int i = 0; i < fileSize; i++)
{
System.out.print((char) buffer.get());
}
inChannel.close();
aFile.close();