我想读取128个字节的文件并放入一个字节数组,用128字节进行处理。这应该遍历文件的整个长度(即每次读取下一个128字节并存储到字节数组中并进行处理)。我目前能够将文件中的所有字节读入单字节数组。
public static void main(String[] args) throws IOException {
Path path = Paths.get("path/t/file");
byte[] bytes = Files.readAllBytes(path); }
任何帮助都将深表感谢。
答案 0 :(得分:1)
您应该只使用FileInputStream:
try {
File file = new File("file.ext");
RandomAccessFile data = new RandomAccessFile(file, "r");
byte[] fullBytes = new byte[(int) file.length()];
byte[] processBytes = new byte[128];
for (long i = 0, len = file.length() / 128; i < len; i++) {
data.readFully(processBytes);
// do something with the 128 bytes (processBytes).
processBytes = ByteProcessor.process(processBytes)
// add the processed bytes to the full bytes array
System.arraycopy(processBytes, 0, fullBytes, processBytes.length, fullBytes.length);
}
} catch (IOException ex) {
// catch exceptions.
}
答案 1 :(得分:0)
这是你可以做的事情。
public void byteStuff()
{
File file= new File("PATHT TO FILE");
FileInputStream input= new FileInputStream(file);
byte[] bytes = new byte[128];
while((input.read(bytes)) != -1)
{
//byte array is now filled. Do something with it.
doSomething(bytes);
}
}