IO流

2022/8/9 6:23:54

本文主要是介绍IO流,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

FileInputStream:

  用于文件读取数据,可以用new创建输入流对象

    InputStream  Input = new FileInputStream();                --InputStream是抽象类,无法实例化,用FileInputStream接收

    byte[] data = new byte[1024];    

 

FileOutputStream:

  向文件中写入数据,如果文件不存在则会创建

    有两个构造方法可以用来创建FileOutputStream对象

    ①OutputStream  f = new  FileOutputStream("D:/java/h");

    ②File f = new File("D:/java/c");

      OutputStream fout = new FileOutPutStream(f);

    如果文件已存在则会覆盖原文件内容, 如果不想覆盖原文件内容,将(f)改为(f.true)   //默认值为f.false

Reader:

  包装FileInputStream流

    Reader reader = new InputStreamReader(xx);

    关闭流时先打开的后关,后打开的先关

 

    乱码问题:①将文件编码设置为ANSI    ②在reader时手动设置为utf-8  -- reader = new InputStreamReader(f,"utf-8")

   -----------------FileReader 相当于Reader   但他不用包装FileInputStream,写法更简单,但是他不能修改字符编码,只能为ANSI(无法进行字符操作)

 

序列化:      

          该类必须实现java.io.Serialization接口

               序列化反序列化:对对象的读写。

          序列化:对象  --->   txt文件   

          反序列化:txt文件   ----->    对象

  

              OutputStream ops = new FileOutputStream();        -------------序列化   

              ObjectOutputStream  oop  =  new  ObjectOutputStream(ops)     -------------序列化        

                  oop.writeObject(stu);

          

              InputStream  ins  =  new  FileInputStream();                               ------------反序列化

              ObjectInputStream  ois  =  new  ObjectInputStream(ins);            ------------反序列化

                    Object  obj  =  ois.readObject();

 

               if(obj  instanceof  Student){

                Student  stu1 = (Student) obj;

                System.out.println(stu1.getName  +  stu1.getAge);

                }

 

 

二进制读取

        读:                                         FileInputStream    fis  =  new FileInputStream(file);

                  DataInputStream  dis  =  new  DataInputStream(fis);

                    byte[]  data  =  new  byte[fis.available()];

                    dis.read(data)                        fis.available这个方法可以在读写操作前先得知数据流里有多少个字节可以读取

             

      写:                  FileOutputStream  fos  =  new  FileOutputStream(file);

                   DataOutputStream  dos  =  new  DataOutputStream(fos);

                           dos.write(data);

 

 

 

 

 

 

 

 

 

    BufferedReader 是支持同步的,而 Scanner 不支持。如果我们处理多线程程序,BufferedReader 应当使用。

    BufferedReader 相对于 Scanner 有足够大的缓冲区内存。

    Scanner 有很少的缓冲区(1KB 字符缓冲)相对于 BufferedReader(8KB字节缓冲),但是这是绰绰有余的。

    BufferedReader 相对于 Scanner 来说要快一点,因为 Scanner 对输入数据进行类解析,而 BufferedReader 只是简单地读取字符序列。



这篇关于IO流的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程