Java语言-45:字节输入流InputStream的常用方法

1、

package IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

/*由于InputStream是抽象类,不能实例化,故在实际开发中一般使用其子实现类FileInputStream进行实例化
 * FileInputStram的一些方法:
 * read() :从此输入流中读取一个数据字节。
 * read(byte[] b):从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
          read(byte[] b, int off, int len) : 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中
 * 
 * */
public class IO_InputStream_FileInputStream_method {

public static void main(String[] args) throws Exception {
// 首先在本项目目录下创建f.txt文件,文件内容为asdfgh
// 创建一个字节文件输入流对象
// 读取文件
FileInputStream f = new FileInputStream("f.txt");
// 判断
// read() :从此输入流中读取一个数据字节。
int by = 0;
while ((by = f.read()) != -1) {
System.out.print((char) by); // asdfgh
}
// 释放资源
f.close();

}
}
package IO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class IO_InputStream_FileInputStream_method2 {

public static void main(String[] args) throws Exception {
// 创建文件输入流对象
FileInputStream f = new FileInputStream("f.txt");
// read(byte[] b, int off, int len) : 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中
byte[] bytes = new byte[1024]; // 此处空间大小为1024或者1024的整数倍
int length = 0;
while ((length = f.read(bytes)) != -1) { // 判断,赋值,循环
System.out.println(new String(bytes, 0, length)); // 带上len的用法 //输出:asdfgh
}

}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值