import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//FileInputStream最终版
public class FileInputStreamTest03 {
public static void main(String[] args) {
//因为FileInputStream有异常需要处理,后面在流使用完毕后应该关闭流,在try语句块内的语句无法被关闭,所以应该在try语句块外面先给变量赋空值
FileInputStream fis=null;
try {
//创建一个FileInputStream对象,传入文件路径
fis=new FileInputStream("C:\\Users\\29949\\IdeaProjects\\chapter11\\src\\tempfile1");
//创建一个byte数组用来读取数据
byte[] bytes=new byte[4];
//定义变量
int readCount=0;
//while循环,流对象调用read方法传入byte数组返回给变量readCount,当变量值为-1时,循环停止
while ((readCount=fis.read(bytes))!=-1){
//将传入的byte数组转换成字符串类型,注意不要写println,因为不要换行
System.out.print(new String(bytes,0,readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
//关闭流
}finally {
if (fis==null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Java基础 FileInputStream传入数组循环读
最新推荐文章于 2025-04-17 11:37:32 发布