亲爱的乐字节的小伙伴们,小乐又来分享Java技术文章了。上一篇写到了IO流,这篇文章着重 谈谈输入流,再下次再说输出流。java
点击回顾上一篇:乐字节Java之file、IO流基础知识和操做步骤数组
字节流和字符流的操做方式几乎彻底同样,只是操做的数据单元不一样而已 。字节流可jvm
以操做全部文件,字符流仅操做纯文本。性能
InputStream和Reader是全部输入流的基类,它们是两个抽象类,是全部输入流的模版,其中定义的方法在全部输入流中均可以使用。学习
在InputStream里包含以下三个方法:编码
在Reader中包含以下三个方法:spa
对比InputStream和Reader 所提供的方法,能够看出这两个基类的功能基本类似。返回结果为-1 时代表到了输入流的结束点。 InputStream 和 Reade 都是抽象的,不能直接建立它们的实例,可使用它们的子类。code
FileInputStream 和 FileReader,它们都是节点流,直接和指定文件关联。 操做方式对象
基本一致。blog
1)、单个字节读取
以FileInputStream为例:
public class SingleFileRead { public static void main(String[] args) { // 一、创建联系 File对象 File file = new File("f:/IO/test.txt"); // 二、选择流 InputStream in = null;// 提高做用域 try { in = new FileInputStream(file); // 三、操做 单个字节读取 long fileLength = file.length(); // 接收实际读取的字节数 // 计数器 System.out.println(fileLength); long num = 0; // 循环读取 while (num < fileLength) { char ch = (char) in.read(); System.out.println(ch); num++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("文件不存在,不能进行下一步操做"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("读取文件失败"); } finally { try { // 四、释放资料 if (in != null) { in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("关闭文件输入流失败"); } } } } 乐字节原创
2)、批量读取(字节|字符重点)
public class ReadFile { public static void main(String[] args) { //一、字节读取:创建联系 File对象 File file=new File("f:/IO/test.txt"); //二、选择流 InputStream in=null;//提高做用域 try { in=new FileInputStream(file); //三、操做 不断读取 缓冲数组 byte[]car=new byte[1024]; int len=0; //接收实际读取的大小 //循环读取 while(-1!=(len=in.read(car))){ //输出,字节数组转成字符串 String info=new String(car,0,len); System.out.println(info); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("文件不存在"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("读取文件失败"); }finally{ try { //四、释放资料 if(in!=null){ in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("关闭文件输入流失败"); } } } } //字符读取一、建立源 File src=new File("f:/char.txt"); //二、选择流 Reader reader=new FileReader(src); //三、读取操做 char[] flush=new char[1024]; int len=0; while(-1!=(len=reader.read(flush))){ //字符数组转换为字符串 String str=new String(flush,0,len); System.out.