gpt4 book ai didi

java - 以较小长度的字节缓冲区 block 的数量读取和写入文件

转载 作者:行者123 更新时间:2023-12-02 02:42:09 25 4
gpt4 key购买 nike

我正在尝试读取固定长度的 ByteBuffer block 中的文件,然后将其存储到 ByteBuffer 列表中,然后在进行一些操作后读取这些 ByteBuffer block 按顺序重建文件。问题是在写入输出文件时 channel 位置没有增加。我不想使用字节数组,因为它们是固定长度的并且文件重建无法正常工作。所以我想知道如何增加文件写入 channel 位置的大小,或任何其他方式来执行此操作。示例代码将不胜感激。这是我的代码片段,

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();

字节缓冲区位置正确,但 outChannel 位置仍为 1048,即 block 大小。

最佳答案

以下内容确实会根据要求维护 ByteBuffer 列表。

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 负责关闭 channel /文件。文件(实用函数)和路径(比文件更通用)很有用。

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

最好不要使用浮点,即使在这里也是如此。

关于java - 以较小长度的字节缓冲区 block 的数量读取和写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com