[英]How to read a specific number of bytes from a file into a bytes array in Java?
我想读取文件的128个字节,并放入一个字节数组中,以对128个字节进行一些处理。 这应该遍历文件的整个长度(即每次读取下一个128个字节并存储到一个字节数组中并进行处理)。 我目前能够将文件中的所有字节读取到一个字节数组中。
public static void main(String[] args) throws IOException {
Path path = Paths.get("path/t/file");
byte[] bytes = Files.readAllBytes(path); }
任何帮助将不胜感激。
您应该只使用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.
}
您可以执行以下操作。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.