以较小长度的字节缓冲区块的数量读写文件

时间:2017-07-24 21:55:59

标签: java bytebuffer filechannel

我正在尝试以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这是块大小。

1 个答案:

答案 0 :(得分:2)

以下内容确实会按要求维护ByteBuffers列表。

String fileName = "hello.txt";
final int chunkSize = 256;
List<ByteBuffer> bufferList = new ArrayList<>();
Path path = Paths.get(fileName);
try (SeekableByteChannel inChannel = Files.newByteChannel(path,
        EnumSet.of(StandardOpenOption.READ))) {
    long size = inChannel.size();
    while (size > 0) {
        ByteBuffer buffer = ByteBuffer.allocate(chunkSize);

        int nread = inChannel.read(buffer);
        if (nread <= 0) {
            break;
        }
        buffer.flip();
        bufferList.add(buffer);
        size -= nread;
    }
}

// write
Path file1 = Paths.get("hello2.txt") ;
try (SeekableByteChannel outChannel = Files.newByteChannel(file1,
        EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))) {
    for (ByteBuffer buffer : bufferList) {
        int nwritten = outChannel.write(buffer);
    }
}

Try-with-resources负责关闭频道/文件。 文件(实用程序功能)和路径(比文件更通用)很有用。

当有chunkSize限制时,需要添加ByteBuffer的新实例。 (因此也可能添加了基础字节数组。)

最好不要使用浮点,即使在这里。