• Java IO<2> 输入/输出流 FileInputStream/FileOutputStream


    输入/输出流

    按操作 数据单位不同分为:流 字节流(8 bit) ,字符流(16 bit)
    按数据流的 流向不同分为: 输入流,输出流
    按流的 角色的不同分为:节点流,处理流

    ![image-20220401104313960](

    )

    字节流

    字节输出流OutputStream

    java.io.OutputStream 抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。

    • public void close() :关闭此输出流并释放与此流相关联的任何系统资源。
    • public void flush() :刷新此输出流并强制任何缓冲的输出字节被写出。
    • public void write(byte[] b) :将 b.length字节从指定的字节数组写入此输出流。
    • public void write(byte[] b, int off, int len) :从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。
    • public abstract void write(int b) :将指定的字节输出流。

    close方法,当完成流的操作时,必须调用此方法,释放系统资源

    FileOutputStream

    java.io.FileOutputStream 类是文件输出流,用于将数据写出到文件。
    构造方法

    • public FileOutputStream(File file) :创建文件输出流以写入由指定的 File对象表示的文件。
    • public FileOutputStream(String name) : 创建文件输出流以指定的名称写入文件。

    当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。

    清空文件写入
    public static void main(String[] args) throws IOException {
        String filePath = "d:" + File.separator + "test.txt";
        File file = new File(filePath);
        FileOutputStream outputStream = new FileOutputStream(file);
        // 输出 a b c
        outputStream.write(97);
        outputStream.write(98);
        outputStream.write(99);
        // 输出换行1
        outputStream.write(new String("\n").getBytes());
        // 输出 “hello”
        String s = "hello";
        byte[] bytes = s.getBytes();
        outputStream.write(bytes);
        // 输出换行2
        outputStream.write(10);
        // 输出部分数组
        outputStream.write(bytes, 1, bytes.length - 1);
        /* output:
                abc
                hello
                ello
        */
        outputStream.close();
    }
    
    1. 虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。
    2. 流操作完毕后,必须释放系统资源,调用close方法。
    追加文件写入
    • public FileOutputStream(File file, boolean append) : 创建文件输出流以写入由指定的 File对象表示的文件。
    • public FileOutputStream(String name, boolean append) : 创建文件输出流以指定的名称写入文件。

    这两个构造方法,参数中都需要传入一个boolean类型的值, true 表示追加数据, false 表示清空原有数据

    写入换行

    回车符 \r 和换行符 \n :
    回车符:回到一行的开头(return)。
    换行符:下一行(newline)。
    系统中的换行:
    Windows系统里,每行结尾是 回车+换行 ,即 \r\n ;
    Unix系统里,每行结尾只有 换行 ,即 \n ;
    Mac系统里,每行结尾是 回车 ,即 \r 。从 Mac OS X开始与Linux统一。

    字节输入流InputStream

    java.io.InputStream 抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。它定义了字节输入流的基本共性功能方法。

    • public void close() :关闭此输入流并释放与此流相关联的任何系统资源。
    • public abstract int read() : 从输入流读取数据的下一个字节。
    • public int read(byte[] b) : 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
    • public int read(byte[] b,int off,int len) : 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。

    FileInputStream

    构造方法
    • FileInputStream(File file) : 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
    • FileInputStream(String name) : 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。

    当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有该文件,会抛出 FileNotFoundException 。

    1. 读取字节: read 方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回 -1
    2. 使用字节数组读取: read(byte[] b) ,每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回 -1
        public static void main(String[] args) throws IOException {
            String filePath = "d:" + File.separator + "test.txt";
            File file = new File(filePath);
            FileInputStream inputStream = new FileInputStream(file);
            // 一个一个读
            System.out.println((char) inputStream.read());
            // 循环读
            int c;
            while ((c = inputStream.read()) != -1) {
                System.out.println((char) c);
            }
            inputStream.close();
            System.out.println("==========");
            // 使用数组读取
            byte[] bytes = new byte[2];
            FileInputStream stream = new FileInputStream(file);
            int len;
            String res = "";
            while ((len = stream.read(bytes)) != -1) {
                res += new String(bytes, 0, len);
            }
            System.out.println(res);
            stream.close();
        }
    

    使用输入输出流复制图片

    public class Copy {
        public static void main(String[] args) throws IOException {
            // 1.创建流对象
            // 1.1 指定数据源
            FileInputStream fis = new FileInputStream("D:\\test.jpg");
            // 1.2 指定目的地
            FileOutputStream fos = new FileOutputStream("test_copy.jpg");
            // 2.读写数据
            // 2.1 定义数组
            byte[] b = new byte[1024];
            // 2.2 定义长度
            int len;
            // 2.3 循环读取
            while ((len = fis.read(b))!=‐1) {
                // 2.4 写出数据
                fos.write(b, 0 , len);
            }
            // 3.关闭资源
            fos.close();
            fis.close();
        }
    }
    

    public int read(byte[] b,int off,int len) :

    public static void main(String[] args) throws IOException {
        String filePath = "d:" + File.separator + "test.txt";
        File file = new File(filePath);
        // 使用数组读取
        byte[] bytes = new byte[1024];
        FileInputStream stream = new FileInputStream(file);
        int len;
        String res = "";
        while ((len = stream.read(bytes)) != -1) {
            res += new String(bytes, 1, len);
        }
        System.out.println(res);
        stream.close();
    }
    

    字符流

    当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。

    java.io.Reader 抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入流的基本共性功能方法。

    • public void close() :关闭此流并释放与此流相关联的任何系统资源。
    • public int read() : 从输入流读取一个字符。
    • public int read(char[] cbuf) : 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中

    字符输入流Reader

    java.io.Reader 抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入
    流的基本共性功能方法。

    • public void close() :关闭此流并释放与此流相关联的任何系统资源。
    • public int read() : 从输入流读取一个字符。
    • public int read(char[] cbuf) : 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。

    FileReader

    • FileReader(File file) : 创建一个新的 FileReader ,给定要读取的File对象。
    • FileReader(String fileName) : 创建一个新的 FileReader ,给定要读取的文件的名称。

    当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream 。

    public static void main(String[] args) throws IOException {
        String filePath = "d:" + File.separator + "test.txt";
        //txt内容为“你好博客园”
        File file = new File(filePath);
        FileReader reader = new FileReader(file);
        int c;
        while ((c = reader.read()) != -1) {
            System.out.print((char) c);
        }
        reader.close();
        System.out.println("==============");
        //使用数组读取,输出如下
        /*
                你好
                博客
                园客
        */
        FileReader fileReader = new FileReader(file);
        char[] cbuf = new char[2];
        String s = "";
        int len;
        while ((len = fileReader.read(cbuf)) != -1) {
            System.out.println(new String(cbuf));
            s += new String(cbuf, 0, len);
        }
        fileReader.close();
        //s=你好博客园
        System.out.println(s);
    }
    

    字符输出流Writer

    java.io.Writer 抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。它定义了字节输出流的基本共性功能方法。

    • void write(int c) 写入单个字符。
    • void write(char[] cbuf) 写入字符数组。
    • abstract void write(char[] cbuf, int off, int len) 写入字符数组的某一部分,off数组的开始索引,len写的字符个数。
    • void write(String str) 写入字符串。
    • void write(String str, int off, int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
    • void flush() 刷新该流的缓冲。
    • void close() 关闭此流,但要先刷新它。

    FileWriter

    java.io.FileWriter 类是写出字符到文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。

    构造方法
    • FileWriter(File file) : 创建一个新的 FileWriter,给定要读取的File对象。
    • FileWriter(String fileName) : 创建一个新的 FileWriter,给定要读取的文件的名称。

    因为内置缓冲区的原因,如果不关闭输出流,无法写出字符到文件中。但是关闭的流对象,是无法继续写出数据的。如果我们既想写出数据,又想继续使用流,就需要 flush 方法了。

    • flush :刷新缓冲区,流对象可以继续使用。
    • close :先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。
    1. 虽然参数为int类型四个字节,但是只会保留一个字符的信息写出。
    2. 未调用close方法,数据只是保存到了缓冲区,并未写出到文件中。
    public static void main(String[] args) throws IOException {
        String filePath = "d:" + File.separator + "test.txt";
        //txt内容为“你好博客园”
        File file = new File(filePath);
        //清空了当前文件
        FileWriter writer = new FileWriter(file);
        writer.write(97);
        writer.write("a");
        writer.write(30222);
        //【注意】关闭资源时,与FileOutputStream不同。
        //如果不关闭,数据只是保存到缓冲区,并未保存到文件。
        writer.close();//输出为:aa瘎
    
        //使用flush
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write('c');
        fileWriter.flush();//此时已经输出c
        fileWriter.write('+');
        fileWriter.flush();
        fileWriter.write('+');
        //输出为c++
        fileWriter.close();
    }
    

    即便是flush方法写出了数据,操作的最后还是要调用close方法,释放系统资源。

    写出其他数据

    1. 写出字符数组 : write(char[] cbuf) 和 write(char[] cbuf, int off, int len) ,每次可以写出字符数组中的数据,用法类似FileOutputStream。
    2. 写出字符串: write(String str) 和 write(String str, int off, int len) ,每次可以写出字符串中的数据,更为方便。
    3. 续写和换行:操作类似于FileOutputStream。
    public static void main(String[] args) throws IOException {
        String filePath = "d:" + File.separator + "test.txt";
        File file = new File(filePath);
        //以追加的形式写
        FileWriter writer = new FileWriter(file,true);
        char[] chars = "c++ java".toCharArray();
        writer.write(chars);
        writer.write("\n");
        writer.write(chars,1,chars.length-1);
        writer.write("\n");
        writer.write("你好",1,1);
        writer.close();
        /*
            c++ java
            ++ java
            好
        */
    }
    

    字符流,只能操作文本文件,不能操作图片,视频等非文本文件。
    当我们单纯读或者写文本文件时 使用字符流 其他情况使用字节流

    JDK自动close释放资源

    使用JDK7优化后的 try-with-resource 语句,该语句确保了每个资源在语句结束时关闭。所谓的资源(resource)是指在程序完成后,必须关闭的对象。

    //格式
    try (创建流对象语句,如果多个,使用';'隔开) {
    // 读写数据    
    } catch (IOException e) {
    	e.printStackTrace();    
    }
    //示例
    public class HandleException {
        public static void main(String[] args) {
           // 创建流对象  
            try ( FileWriter writer = new FileWriter("test.txt"); ) {
                // 写出数据
                writer.write("c++"); 
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    JDK9中 try-with-resource 的改进,对于引入对象的方式,支持的更加简洁。被引入的对象,同样可以自动关闭,无需手动close.

    // 被final修饰的对象
    final Resource resource1 = new Resource("resource1");
    // 普通对象
    Resource resource2 = new Resource("resource2");
    // 引入方式:创建新的变量保存
    try (Resource r1 = resource1;
         Resource r2 = resource2) {
         // 使用对象
    }
    //示例
    public class TryDemo {
        public static void main(String[] args) throws IOException {
           // 创建流对象 
            final  FileReader fr  = new FileReader("in.txt");
            FileWriter fw = new FileWriter("out.txt");
           // 引入到try中 
            try (fr; fw) { 
               while ((b = fr.read())!=‐1) {   
                 fw.write(b);    
               }  
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  • 相关阅读:
    Java—数据库技术
    Java—泛型
    Java—图形处理
    Java—网络技术
    vb.net 分割byte数组的方法SplitBytes
    动态支付宝转账码可指定金额备注无限秒生成的方法
    关于支付宝个人账户免签收款自动备注
    vb.net MakeWParam
    Vb.net MakeLong MAKELPARAM 合并整数代码
    百度图片objURL解密vb.net版
  • 原文地址:https://www.cnblogs.com/aslanvon/p/16092476.html
Copyright © 2020-2023  润新知