读
问题:读取一个文件按读取的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.cl