FileInputStram入门

时间:2023-03-09 03:29:43
FileInputStram入门

1、read() 读取一个字节

@Test
 public void test1() throws Exception{
  //1、指定文件读取路径
  String filePath = "E:\\新建文本文档.txt"; //该文档中的内容为 ab cdefg
  
  //2、读取文本
  FileInputStream fis = new FileInputStream(filePath); //读取文本
  int c1 = fis.read();   //以字节方式读取下一个字符 返回该字节的ASCII码
  int c2 = fis.read();
  int c3 = fis.read();
  int c4 = fis.read();
  int c5 = fis.read();
  int c6 = fis.read();
  int c7 = fis.read();
  int c8 = fis.read();
  int c9 = fis.read();   //当读到文件末尾时会返回-1
  
  System.out.println(c1);
  System.out.println(c2);
  System.out.println(c3);
  System.out.println(c4);
  System.out.println(c5);
  System.out.println(c6);
  System.out.println(c7);
  System.out.println(c8);
  System.out.println(c9);
  
  //3、关闭流
  fis.close();
 } //优化该方法
@Test
 public void test1() throws Exception{
  //1、指定文件读取路径
  String filePath = "E:\\新建文本文档.txt"; //该文档中的内容为 ab cdefg
  
  //2、读取文本
  FileInputStream fis = new FileInputStream(filePath); //读取文本
  int temp = 0;
  while((temp = fis.read()) != -1){
   System.out.println(temp);
  }
  
  //3、关闭流
  fis.close();
 }

2、read(byte[])  读取一个字节数组

@Test
public void test2() throws Exception{ //1、声明文件路径
String filePath = "E:\\新建文本文档.txt"; //该文档中的内容为 ab cdefg //2、读取文本
FileInputStream fis = new FileInputStream(filePath); //读取文本
byte[] bytes = new byte[3]; //声明一个长度为3的字节数组 int c1 = fis.read(bytes); //依次读取3个字节,并返回所读取到的字节数
System.out.println(c1);
System.out.println(new String(bytes)); //将读取到的字节数组转换成字符串 int c2 = fis.read(bytes);
System.out.println(c2);
System.out.println(new String(bytes)); int c3 = fis.read(bytes); //最后只剩两字节
System.out.println(c3);
System.out.println(new String(bytes));
/**
* 这一组的输出结果不是预期得到的结果,因为c3=2,但转换成字符串的结果是fge.这里因为在读到最后fg时,fg将上层
* cde中的cd替换掉了,所以输出的结果是fge。正确的写法应该是
*/
System.out.println(new String(bytes, 0, c3)); int c4 = fis.read(bytes); //读取到文本末尾,返回-1
System.out.println(c4); //3、关闭流
fis.close();
} //优化后写法
@Test
public void test2() throws Exception{
//1、声明文件路径
String filePath = "E:\\新建文本文档.txt"; //该文档中的内容为 ab cdefg //2、读取文本
FileInputStream fis = new FileInputStream(filePath); //读取文本
byte[] bytes = new byte[1024]; //声明一个长度为1024的字节数组,即每次读取1K的数据
int temp = 0;
while((temp = fis.read(bytes)) != -1){
System.out.println(new String(bytes, 0 ,temp));
} //3、关闭流
fis.close();
}

3、available()方法:返回流中剩余的估计字节数

@Test
public void test4() throws Exception{
//1、声明文件路径
String filePath = "E:\\新建文本文档.txt"; //该文档中的内容为 ab cdefg
//2、读取文本
FileInputStream fis = new FileInputStream(filePath); //读取文本 System.out.println(fis.available()); //返回结果为8
System.out.println(fis.read()); //调用read方法
System.out.println(fis.available()); //返回结果为7 fis.close();
}

4、skip(long n)方法,跳过字节数

@Test
public void test5() throws Exception{
//1、声明文件路径
String filePath = "E:\\新建文本文档.txt"; //该文档中的内容为 ab cdefg
//2、读取文本
FileInputStream fis = new FileInputStream(filePath); //读取文本 System.out.println(fis.available()); //返回结果为8
fis.skip(2); //跳过两个字节
System.out.println(fis.available()); // 估计可用字节数为6 fis.close();
}