gpt4 book ai didi

java - 在 Java 中将文件的一部分复制到字节数组

转载 作者:行者123 更新时间:2023-12-01 16:35:27 25 4
gpt4 key购买 nike

有什么方法可以读取要导入到字节数组中的文件的一部分吗?

我想知道如何操作,因为我只能找到将整个文件转换为字节数组的方法,这是一个非常消耗内存的操作。

最佳答案

我会使用RandomAccessFile:

public static byte[] readFileSegment(File file, long index, int count) {
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte[] buffer = new byte[count];
try {
raf.seek(index);
raf.readFully(buffer, 0, count);
return buffer;
} finally {
raf.close();
}
}

还有内存映射文件、NIO 等其他替代方案 - 但这应该很简单。

关于java - 在 Java 中将文件的一部分复制到字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9670341/

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