FileInputStream简单用法

FileInputStream 从文件系统中的某个文件中获得输入字节。

使用FileInputStream读取文件数据的步骤:
1. 找到目标文件
2. 建立数据的输入通道。
3. 读取文件中的数据。
4. 关闭资源.

具体使用方式如下:

方式一:
”’
public static void readTest1() throws IOException{
//1. 找到目标文件
File file = new File(“d:/FileTest/b.txt”);
//建立数据的输入通道。
FileInputStream fileInputStream = new FileInputStream(file);
//读取文件中的数据
int content = fileInputStream.read(); // read() 读取一个字节的数据,把读取的数据返回。
System.out.println(“读到的内容是:”+ (char)content);
//关闭资源 实际上就是释放资源。
fileInputStream.close();
}
”’
方式二:
public static void readTest2() throws IOException{
long startTime = System.currentTimeMillis();
//找到目标文件
File file = new File(“F:\美女\1.jpg”);
//建立数据的输入通道
FileInputStream fileInputStream = new FileInputStream(file);
//读取文件的数据
int content = 0; //声明该变量用于存储读取到的数据
while((content = fileInputStream.read())!=-1){
System.out.print((char)content);
}
//关闭资源
fileInputStream.close();
}

方式三:
public static void readTest3() throws IOException{
//找到目标文件
File file = new File(“F:\a.txt”);
//建立数据的输入通道
FileInputStream fileInputStream = new FileInputStream(file);
//建立缓冲字节数组,读取文件的数据。
byte[] buf = new byte[1024]; //相当于超市里面的购物车。
int length = fileInputStream.read(buf); // 如果使用read读取数据传入字节数组,那么数据是存储到字节数组中的,而这时候read方法的返回值是表示的是本次读取了几个字节数据到字节数组中。
System.out.println(“length:”+ length);
//使用字节数组构建字符串
String content = new String(buf,0,length);
System.out.println(“内容:”+ content);
//关闭资源
fileInputStream.close();
}

方式四:
public static void readTest4() throws IOException{
long startTime = System.currentTimeMillis();
//找到目标文件
File file = new File(“F:\美女\1.jpg”);
//建立数据的输入通道
FileInputStream fileInputStream = new FileInputStream(file);
//建立缓冲数组配合循环读取文件的数据。
int length = 0; //保存每次读取到的字节个数。
byte[] buf = new byte[1024]; //存储读取到的数据 缓冲数组 的长度一般是1024的倍数,因为与计算机的处理单位。 理论上缓冲数组越大,效率越高
while((length = fileInputStream.read(buf))!=-1){ // read方法如果读取到了文件的末尾,那么会返回-1表示。
System.out.print(new String(buf,0,length));
}
//关闭资源
fileInputStream.close();
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值