zoukankan      html  css  js  c++  java
  • 2020/7/31 JAVA之IO流(二)

    一、字节流

      1、字节输出流OutputStream

        OutputStream此抽象类,是表示输出字节流的所有类的超类。操作的数据都是字节,定义了输出字节流的基本共性功能方法。

        输出流中定义都是写write方法,如下图:

         OutputStream有很多子类,其中子类FileOutputStream可用来写入数据到文件。

         FileOutputStream类,即文件输出流,是用于将数据写入 File的输出流。

         构造方法:

        

         将数据写到文件中,代码演示:

    public class FileOutputStreamDemo {
        public static void main(String[] args) throws IOException {
            //需求:将数据写入到文件中。
            //创建存储数据的文件。
            File file = new File("c:\file.txt");
            //创建一个用于操作文件的字节输出流对象。一创建就必须明确数据存储目的地。
            //输出流目的是文件,会自动创建。如果文件存在,则覆盖。
            FileOutputStream fos = new FileOutputStream(file);
            //调用父类中的write方法。
            byte[] data = "abcde".getBytes();
            fos.write(data);
            //关闭流资源。
            fos.close();
        }
    }

      

       在后面添加true可以在文件中续写

      给文件中续写数据和换行,代码演示:

    public class FileOutputStreamDemo2 {
        public static void main(String[] args) throws Exception {
            File file = new File("c:\file.txt");
            FileOutputStream fos = new FileOutputStream(file, true);
            String str = "
    "+"aaa";
            fos.write(str.getBytes());
            fos.close();
        }
    }

      2、IO异常的处理

    public class FileOutputStreamDemo3 {
        public static void main(String[] args) {
            File file = new File("c:\file.txt");
            //定义FileOutputStream的引用
            FileOutputStream fos = null;
            try {
                //创建FileOutputStream对象
                fos = new FileOutputStream(file);
                //写出数据
                fos.write("abcde".getBytes());
            } catch (IOException e) {
                System.out.println(e.toString() + "----");
    throw new RuntimeException("文件写入失败,重试");
    
            } finally {
                //一定要判断fos是否为null,只有不为null时,才可以关闭资源
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        throw new RuntimeException("关闭资源失败");
                    }
                }
            }
        }
    }

      3、字节输入流InputStream

         int read():读取一个字节并返回,没有字节返回-1.

         int read(byte[]): 读取一定量的字节数,并存储到字节数组中,返回读取到的字节数。

        InputStream有很多子类,其中子类FileInputStream可用来读取文件内容。

        FileInputStream 从文件系统中的某个文件中获得输入字节。

       4、FileInputStream类读取数据read方法

       从文件中读取数据,代码演示:

    public class FileInputStreamDemo {
        public static void main(String[] args) throws IOException {
            File file = new File("c:\file.txt");
            //创建一个字节输入流对象,必须明确数据源,其实就是创建字节读取流和数据源相关联。
            FileInputStream fis = new FileInputStream(file);
            //读取数据。使用 read();一次读一个字节。
            int ch = 0;
            while((ch=fis.read())!=-1){
                System.out.println("ch="+(char)ch);
            }
            // 关闭资源。
            fis.close();
        }
    }

      在读取文件中的数据时,调用read方法,每次只能读取一个,太麻烦了,

      于是我们可以定义数组作为临时的存储容器,这时可以调用重载的read方法,一次可以读取多个字符。

    public class FileInputStreamDemo2 {
        public static void main(String[] args) throws IOException {
            /*
             * 演示第二个读取方法, read(byte[]);
             */
            File file = new File("c:\file.txt");
            // 创建一个字节输入流对象,必须明确数据源,其实就是创建字节读取流和数据源相关联。
            FileInputStream fis = new FileInputStream(file);        
            //创建一个字节数组。
            byte[] buf = new byte[1024];//长度可以定义成1024的整数倍。        
            int len = 0;
            while((len=fis.read(buf))!=-1){
                System.out.println(new String(buf,0,len));
            }
            fis.close();
        }
    }

    二、字符流

      1、字符输入流Reader

         read():读取单个字符并返回

         read(char[]):将数据读取到数组中,并返回读取的个数。

      2、FileReader类

        打开FileReaderAPI介绍。用来读取字符文件的便捷类。

        此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的

        

       3、使用FileReader读取包含中文的文件

    public class CharStreamDemo {
        public static void main(String[] args) throws IOException {
            //给文件中写中文
            writeCNText();
            //读取文件中的中文
            readCNText();
        }    
        //读取中文
        public static void readCNText() throws IOException {
            FileReader fr = new FileReader("D:\test\cn.txt");
            int ch = 0;
            while((ch = fr.read())!=-1){
                //输出的字符对应的编码值
                System.out.println(ch);
                //输出字符本身
                System.out.println((char)ch);
            }
        }
        //写中文
        public static void writeCNText() throws IOException {
            FileOutputStream fos = new FileOutputStream("D:\test\cn.txt");
            fos.write("欢迎你".getBytes());
            fos.close();
        }
    }

      4、字符输出流Writer

        

         FileWriter

        构造方法:

        

       5、FileWriter写入中文到文件中,写入字符到文件中,先进行流的刷新,再进行流的关闭。

    public class FileWriterDemo {
        public static void main(String[] args) throws IOException {
            //演示FileWriter 用于操作文件的便捷类。
            FileWriter fw = new FileWriter("d:\text\fw.txt");
            fw.write("你好谢谢再见");//这些文字都要先编码。都写入到了流的缓冲区中。
            fw.flush();
            fw.close();
        }
    }

      6、flush()和close()的区别?

    flush():将流中的缓冲区缓冲的数据刷新到目的地中,刷新后,流还可以继续使用。

    close():关闭资源,但在关闭前会将缓冲区中的数据先刷新到目的地,否则丢失数据,然后在关闭流。流不可以使用。

    如果写入数据多,一定要一边写一边刷新,最后一次可以不刷新,由close完成刷新并关闭。

  • 相关阅读:
    Oracle不常用SQL
    C# xml 读xml、写xml、Xpath、Xml to Linq、xml添加节点 xml修改节点
    Oracle常见错误:ORA-06550、ORA-00911、ORA-02085
    IIS设置允许跨域
    npm和yarn 切换为国内镜像(淘宝镜像)
    Wordpress 所有 hook 钩子
    【C#】WPF多线程登录需求中报错 “调用线程无法访问对象,因为另一个线程拥有该对象“
    【C#】 WPF 中WebBrowser拖动来移动窗口,改变窗口位置
    【Java】Hibernate一级缓存测试分析
    javac编译单文件、多文件引入jar包、-cp解决无法加载主类问题
  • 原文地址:https://www.cnblogs.com/luzhijin/p/13411127.html
Copyright © 2011-2022 走看看