FileInputStream 读取文件内容

超、凢脫俗 2022-05-20 04:15 322阅读 0赞
  1. public class Test {
  2. public static void main(String[] args) throws IOException {
  3. final String path = "D:/1.txt";
  4. //1、得到数据文件
  5. File file = new File(path);
  6. //2、建立数据通道
  7. FileInputStream fileInputStream = new FileInputStream(file);
  8. byte[] buf = new byte[1024];
  9. int length = 0;
  10. //循环读取文件内容,输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
  11. //当文件读取到结尾时返回 -1,循环结束。
  12. while((length = fileInputStream.read(buf)) != -1){
  13. System.out.print(new String(buf,0,length));
  14. }
  15. //最后记得,关闭流
  16. fileInputStream.close();
  17. }
  18. }

读取结果:

70

FileInputStream类的其他常用方法:

注:以下代码的输出均以上面的1.txt文件为例。

1、available()

返回类型: int

作用:返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。即输入流中当前的字节数。

  1. System.out.println(fileInputStream.available());

输出:10

2、skip(long n)

返回类型:long

作用:从输入流中跳过并丢弃n个字节的数据

  1. System.out.println(fileInputStream.skip(4));

输出:4

跳过前面4个字节,所以读取到的数据为: ,世界(一个汉字等于两个字节)

70 1

3、read()

返回类型:int

作用:从输入流中读取一个数据字节

  1. System.out.println(fileInputStream.read());

输出:196

4、read(byte[] b,int off,int len)

返回类型:int

作用:从输入流中读取len个字节的数据到byte数组中,数据存放在byte数组中从off开始后的len个空间内。

  1. System.out.println(fileInputStream.read(buf,3,4));
  2. System.out.println(new String(buf,0,7));

输出: 从输入流中读取4个字节数据,存放到buf数组的 3,4,5,6个空间里,所以在输出的时候,buf前3个空间为空,输出□,后面4个空间输出对应的值:你好。

70 2

发表评论

表情:
评论列表 (有 0 条评论,322人围观)

还没有评论,来说两句吧...

相关阅读