FileInputStream利用缓冲数组读取数据

时间:2023-03-09 05:34:40
FileInputStream利用缓冲数组读取数据
package cd.itcast.fileinputstream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; public class Demo1 {
public static void main(String[] args) throws IOException {
//目标文件
File file =new File("E:\\a.txt");
//创建通道
FileInputStream fileInputStream = new FileInputStream(file);
//创建缓冲数组
byte[] buf = new byte[1024];
//用数组去读取数据,此时read()返回,读取的数量,当读到空时,返回-1.
while (fileInputStream.read(buf)!=-1) {
System.out.println("内容:"+new String(buf));
}
//关闭
fileInputStream.close();
}
}

注意:

最后要关闭资源  fileInputStream.close();假如不释放资源,其他程序是不能操作该资源的。比如,不能删除正在被使用的资源。

相关文章