公共类测试{ publicstaticvoidmain (字符串[ ] args ) throwsioexception ) finalstringpath='d:/1.txt '; //1、获取数据文件文件=新文件(路径); //2、数据通道fileinputstreamfileinputstream=new file inputstream (file ); byte[] buf=new byte[1024]; int length=0; //在循环中读取文件内容,输入流中最大buf.length字节的数据被读取到一个buf数组中,返回类型为读取的字节数。 //文件读取到最后后返回-1,循环结束。 while ((length=file inputstream.read ) ) buf )!=-1 ) system.out.print (新字符串(buf,0,length ) ); 请记住(//最后,关闭fileInputStream.close )中的流程; }读取结果:
FileInputStream类的其他常用方法:
注:以下代码的输出以上面的1.txt文件为例。
1、可用() )
返回类型: int
作用:返回从此输入流读取(或跳过)的估计剩馀字节数,而不会阻止为此输入流调用的下一个方法。 也就是说,输入流的当前字节数。
system.out.println (file inputstream.available (); 输出: 10
2、skip (长时间)。
返回类型:长
角色:从输入流中跳过并丢弃n字节的数据
system.out.println (文件inputstream.skip (4); 输出: 4
因为跳过了前面的4个字节,所以读取的数据是、世界(一个汉字等于两个字节) )。
3、导线() )。
返回类型: int
角色:从输入流读取数据字节
system.out.println (file inputstream.read (); 输出: 196
4、read(byte[]b,int off,int len ) )。
返回类型: int
角色将len字节数据从输入流读取到字节数组中。 数据存储在从byte数组的off开始的len个空间中。
system.out.println (文件输入.读取) buf,3,4 ); 系统. out.println (new string ) buf,0,7 ); 输出:从输入流读取4字节的数据,并将其存储在buf数组的3、4、5、6个区域中。 因此,在输出时,buf的前三个区域为空,输出,后四个区域输出相应的值。 你好。