java io(字符、字节流)基础

     1、流是一组有起点有终点的顺序字节集合,抽象了数据传输,抽象为许多类。

    2、字符流和字节流

    字节流处理所有数据类型,字符流只处理字符类型的数据。

    字节流不会使用到缓冲区的,文件本身的直接操作。

   优先使用字节流(硬盘上的所有数据都是以字节的形式存储的)。

  3、io流对象

    A、 InputStream是所有输入字节流的父类,是抽象的。子类有很多介质流,根据不同的介质(StringBuffer,数组,本地文件)读取数据。System.in

     核心代码

      

 File f=new File("文件路径");
InputStream in =new FileInputStream(f);//父类的引用指向子类的对象
byte[]b=new byte[1024];//用数组存文件的字节
int len=in.read(b);//len为读入的长度
in.close();//关闭字节流
System.out.println(new String(b,0,len));//将字节转化为字符串

 B、OutputStream 是所有的输出字节流的父类,它是一个抽象类。

  核心代码

扫描二维码关注公众号,回复: 534331 查看本文章
File f=new File(文件路径);
OutputStream out=new FileOutputStream(f);
// OutputStream out =newFileOutputStream(f,true);//true表示追加模式,否则为覆盖
String str="sdfghgghmgfgfhm";
byte[] b=str.getBytes();//将字符串转化为字节
  for (int i = 0; i < b.length; i++) {
           out.write(b[i]);
       }
       out.close();

 C、Reader是所有的输入字符流的父类,介质流为CharReader,StringReader,从char数组和String里提取数据。

InputStreamReader 是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。FileReader可以说是一个达到此功能、常用的工具类,在其源代码中明显使用了将FileInputStream 转变为Reader 的方法。我们可以从这个类中得到一定的技巧。Reader 中各个类的用途和使用方法基本和InputStream 中的类使用一致

   核心代码:

  

File f=new File(文件名);
  char[] ch=new char[100];
  Reader reader=new FileReader(file);
int temp=0;
int count=0;
while((temp=reader.read())!=-1)
{
ch[count++]=(char)temp;
}
read.close();
System.out.println(new String(ch,0,count));

 D、BufferedReader 很明显就是一个装饰器,它和其子类负责装饰其它Reader 对象。

 实例,实现读取中文的字节流。

核心代码

  BufferedReader buf = new BufferedReader(
                new InputStreamReader(System.in));//将字节流转为字符流,同时可以缓冲
       String str = null;
       System.out.println("请输入内容");
       try{
           str = buf.readLine();
       }catch(IOException e){
           e.printStackTrace();
       }
       System.out.println("你输入的内容是:" + str);

 

猜你喜欢

转载自1509930816.iteye.com/blog/2147347
今日推荐