读
问题:读取一个文件按读取的byte[]输出时输出超出文件内容
问题发生示例: 有文件a.txt,内容为 ‘12345 \n 12345 \n 123’,通过如下代码输出结果为’12345 \n 12345 \n 12312345\n’ 即表现形式是输出超了
public class Demo1 {
public static void main(String[] args) throws IOException {
File f = new File("filePath");
FileInputStream fis = new FileInputStream(f);
FileChannel channel = fis.getChannel();
ByteBuffer allocate = ByteBuffer.allocate(1024);
int i = -1;
while ((i = channel.read(allocate)) != -1) {
allocate.flip();
byte[] array = allocate.array();
System.out.println(new String(array));
allocate.clear();
}
channel.close();
// fis.close();
}
}
原因:调用byteBuffer.clear OR byteBuffer.compact时 byteBuffer内部的byte数组未被初始化,仅仅是重置了状态标识字段
public class Demo1 {
public static void main(String[] args) throws IOException {
File f = new File("filePath");
FileInputStream fis = new FileInputStream(f);
FileChannel channel = fis.getChannel();
ByteBuffer allocate = ByteBuffer.allocate(1024);
int i = -1;
while ((i = channel.read(allocate)) != -1) {
allocate.flip();
byte[] array = allocate.array();
// -----注意这里 在读取最后一个不完整的byte数组时,获取读取字节数做数组切片
if (allocate.remaining() != 1024) {
System.out.println(new String(Arrays.copyOfRange(array, 0, allocate.remaining())));
} else {
System.out.println(new String(array));
}
// -------------------------------
allocate.get(array);
allocate.clear();
}
channel.close();
// fis.close();
}
}
上面的----夹着的代码也可替换为如下代码
byte[] buf = new byte[allocate.remaining()];
allocate.get(buf);
上面最后一行没有关闭fis.close是因为channel.close调用到最后适合fis.close一样的效果,如下图
channel.close