IO流-----(字节流)

以stream结尾的称为万能流(字节流),否则为字符流

1.java流的概述:

  文件通常是由一串的字节或字符组成,组成文件的字节序列称为字节流,组成文件的字符序列称为字符流。

2.Java中根据流的方向可以分为:输入流和输出流

  输入流:输入流是将文件或其他输入设备的数据加载到内存的过程

  输出流:输出流是将内存中的数据保存到文件或其他输入设备中

3.文件是由字节或字符构成,那么将文件加载到内存或者将文件输出到文件,需要输入流和输出流的支持,那么在JAVA语言中又把输入和输出流分为两种:

                        字节输入流、字节输出流            字符输入流、字符输出流

扫描二维码关注公众号,回复: 3462683 查看本文章

3.1 Inputstream(字节输入流):inputstream是一个抽象的类,所有实现了inputstream类的都是字节输入流,主要了解一下子类即可:

 

范例:

public class Test{

  public static void main(String[] args) throws Exception{

  //创建一个输入流

  InputStream in=new FileInputStream("c:/a.txt");

  //定义一个临时变量

  int temp=0;

  while((temp=in.read())!=-1){

  System.out.println((char)temp);

    }

  }

}

3.2 OutputStream(字节输出流):OutputStream是一个抽象的类,所有实现了这个类的都是字节输出流

如果调用了close()方法,那么会自动调用flush()方法,但是建议手动显示的去调用flush()方法

范例:

public class Test {

  public static void main(String[] args) {
  //创建一个输出字节流
  OutputStream out = null;
  try {
    out = new FileOutputStream("c:/b.txt");
    out.write(123);
    //必须调用flush或close
    out.flush();
  } catch (Exception e) {
    e.printStackTrace();
  }finally {
    try {
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
      }
    }
  System.out.println("success");
  }
}

jdk1.8新特性自动关闭:

范例:

public class Test{

  public static void main(String[] args){

  try(OutputSreeam out =new FileOutputStream("c:/c.txt");){

  //创建一个输出字节流

  out.write(1);

  //必须调用flush方法

  out.flush();

  }catch(Exception e){

  e.printStackTrace();

  }

  System.out.println(success);

  }  

}

猜你喜欢

转载自www.cnblogs.com/heshiping/p/9750608.html