我試圖讀取ByteBuffer
塊中的文件,然後將其存儲到ByteBuffer
列表中,然後在某些操作之後按順序讀取這些ByteBuffer
塊重建文件。問題在於寫入輸出文件通道的位置不增加。 我不想使用字節數組,因爲它們的長度是固定的,文件重建不能正常工作。 所以我想知道如何增加文件寫入通道位置的大小,或任何其他方式來做這個操作。示例代碼將不勝感激。 這裏是我的代碼片段,以較小長度的字節緩衝區塊數讀寫文件
file = new File(fileName); // hello.txt - 20 MB size
fis = new FileInputStream(file);
inChannel = fis.getChannel();
double maxChunkSequenceNoFloat = ((int)inChannel.size())/chunkSize;
int maxChunkSequenceNo = 1;
if(maxChunkSequenceNoFloat%10 > 0) {
maxChunkSequenceNo = ((int)maxChunkSequenceNoFloat)+1;
} else if(maxChunkSequenceNoFloat%10 < 0) {
maxChunkSequenceNo = 1;
} else {
maxChunkSequenceNo = (int)maxChunkSequenceNoFloat;
}
maxChunkSequenceNo = (maxChunkSequenceNo == 0) ? 1 : maxChunkSequenceNo;
ByteBuffer buffer = ByteBuffer.allocate(chunkSize);
buffer.clear();
while(inChannel.read(buffer) > 0) {
buffer.flip();
bufferList.add(buffer);
buffer.clear();
chunkSequenceNo++;
}
maxChunkSequenceNo = chunkSequenceNo;
// write
File file1 = new File("hello2.txt") ;
buffer.clear();
FileOutputStream fos = new FileOutputStream(file1);
FileChannel outChannel = fos.getChannel();
chunkSequenceNo = 1;
for(ByteBuffer test : bufferList) {
writeByteCount += outChannel.write(test);
//outChannel.position() += writeByteCount;'
System.out.println("main - channelPosition: "+outChannel.position()
+" tempBuffer.Position: "+test.position()
+" limit: "+test.limit()
+" remaining: "+test.remaining()
+" capacity: "+test.capacity());
}
BufferedReader br = new BufferedReader(new FileReader(file1));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
outChannel.close();
fos.close();
ByteBuffer的立場是正確的,但outChannel位置保持在1048這是塊的大小。
保持簡單和(部分)使用字節數組。 FileReader使用默認的平臺編碼。 –
這不僅僅是關於我的代碼,而是處理我的數據的類需要ByteBuffers,所以我在問題中明確表示,直接使用字節數組是毫無疑問的。 – andi99
你只使用一個緩衝區,所以你的代碼根本不符合你的描述。 – EJP