标签:fis 字节 read bytes FileInputStream new byte 输入 读取
字节输入流一次读取多个字节
字节输入流一次读取多个字节的方法:
int read(byte[] b)从输入流中读取一定数量的字节 并将其存储在缓冲区数字b中
明确两件事情:
1.方法的参数byte[]的作用
起到缓冲作用 存储每次读取到的多个字节
数组的长度一把定义为1024(1kb)或者1024的整数倍
2.方法的返回值int是什么
每次读取到有效字节个数
代码:
public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("E:\\dest\\a.txt"); //使用FileInputStream对象中的方法read读取文件 byte[] bytes = new byte[2]; int read = fis.read(bytes); System.out.println(bytes); System.out.println(read); System.out.println(Arrays.toString(bytes)); System.out.println(new String(bytes)); //关闭流释放资源 fis.close(); }
a.txt
运行结果:
执行流程图:
这里我们也可以使用while循环
代码:
public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("E:\\dest\\a.txt"); //使用FileInputStream对象中的方法read读取文件 byte[] bytes = new byte[1024]; int len=0; while ((len=fis.read(bytes))!=-1){ System.out.println(new String(bytes)); } //关闭流释放资源 fis.close(); }
运行结果:
public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("E:\\dest\\a.txt"); //使用FileInputStream对象中的方法read读取文件 byte[] bytes = new byte[1024]; int len=0; while ((len=fis.read(bytes))!=-1){ System.out.println(new String(bytes,0,len)); } //关闭流释放资源 fis.close(); }
这样写可以防止数组位置浪费
运行结果:
标签:fis,字节,read,bytes,FileInputStream,new,byte,输入,读取 来源: https://www.cnblogs.com/aimz01/p/16489951.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。