Io流

93 阅读6分钟

IO

编码、解码、乱码

public class Test2 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        // 1.编码:字符串变成 byte[]
        String s = "aW接大";
​
        byte[] bytes = s.getBytes(); // 默认是UTF-8编码格式
        System.out.println(Arrays.toString(bytes));
​
        byte[] bytes1 = s.getBytes("GBK");
        System.out.println(Arrays.toString(bytes1));
​
        // 2. 解码:byte[] 变成字符串
        String s1 = new String(bytes); // 默认是UTF-8
        System.out.println(s1);
​
        String s2 = new String(bytes1, "GBK");
        System.out.println(s2);
​
        // 3. 乱码:编码方式和解码方式不同,会导致乱码 (如果只有英文或数字,不会乱码)
        String s3 = new String(bytes, "GBK"); // UTF-8编,GBK解
        System.out.println(s3);
​
        String s4 = new String(bytes1); // GBK编,UTF-8解
        System.out.println(s4);
​
    }
}

FileInputStream读内容

public class FileInputStreamTest2 {
    public static void main(String[] args) throws IOException {
        // 1、创建一个字节输入流对象代表字节输入流管道与源文件接通。
        FileInputStream is = new FileInputStream("day08\src\com\itheima\d4_byte_stream\itheima01.txt");
​
        // 2、开始读取文件中的字节数据:每次读取多个字节。
        //  public int read(byte b[]) throws IOException
        //  每次读取多个字节到字节数组中去,返回读取的字节数量,读取完毕会返回-1.
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            String s = new String(buffer, 0, len);
            System.out.println(s);
        }
​
        // 关闭连接
        is.close();
    }
}

FileOutputStream写内容

public class FileOutputStreamTest4 {
    public static void main(String[] args) throws IOException {
        // 1、创建一个字节输出流管道与目标文件接通。
​
        // 注意:默认是覆盖
        // FileOutputStream fos = new FileOutputStream("day08\src\com\itheima\d4_byte_stream\itheima02.txt");
​
        // public FileOutputStream(String name, boolean append ):append=true,代表追加
        FileOutputStream fos = new FileOutputStream("day08\src\com\itheima\d4_byte_stream\itheima02.txt", true);
​
        // write()方法,写入数据
        fos.write('W');
        fos.write('E');
        fos.write('R');
​
        // 写多个字节
        String s = "今晚奖励自己一顿大餐";
        fos.write(s.getBytes());
​
        // 限制写十个字节
        fos.write(s.getBytes(), 0, 10);
​
        // 写特殊符号
        fos.write("\n\r".getBytes());
​
        // 关闭连接
        fos.close();
    }
}

复制图片(基于字节流)

try-with-resource

public class Test3 {
    public static void main(String[] args) {
        // 以复制文件代码案例,来进行try-with-resource优化
​
        try (
                FileInputStream is = new FileInputStream("day08\src\com\itheima\d5_resource\qqq.txt");
                FileOutputStream fos = new FileOutputStream("day08\src\com\itheima\d5_resource\qqq2.txt");
        ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
​
        } catch (Exception e) {
            e.printStackTrace();
        }
​
    }
}

try-catch-finally

public class Test {
    public static void main(String[] args) {
        // try-catch-finally改造图片复制
        // ctrl + alt + T :为包裹住的代码,生成try-catch-finally
        FileInputStream is = null;
        FileOutputStream fos = null;
        try {
            is = new FileInputStream("day08\src\com\itheima\d5_resource\qqq.txt");
            fos = new FileOutputStream("day08\src\com\itheima\d5_resource\qqq2.txt");
​
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
​
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
​
        }
    }
}

读含汉字文件(try-with-resource写法)

public class FileReaderTest1 {
    public static void main(String[] args) {
        // try-with-resource写法,自动关流
        try (
                // 创建 FileReader对象,用于读取包含汉字的文件
                FileReader reader = new FileReader("day09\src\itheima\d1_char_stream\abc.txt");
        ) {
​
            // int i = reader.read();
            // System.out.println((char) i);
​
            // 创建一个char数组,每次读取1024个字符
            char[] buffer = new char[1024];
            int len;
            while ((len = reader.read(buffer)) != -1) {
                // 将读取的多个字符转为String对象,并打印
                String s = new String(buffer, 0, len);
                System.out.println(s);
            }
​
        } catch (Exception e) {
            e.printStackTrace();
        }
​
    }
}

写含汉字文件(try-catch-finally)

public class FileWriterTest2 {
    public static void main(String[] args) {
        FileWriter writer = null;
        try {
            // 掌握文件字符输出流:写字符数据出去
            // FileWriter writer = new FileWriter("day09\src\itheima\d1_char_stream\novel.txt");
            writer = new FileWriter("day09\src\itheima\d1_char_stream\novel.txt", true);
​
            writer.write('A');
            writer.write('龙');
​
            writer.write("我TM写写写写写");
​
            String s = "sh龙dbaidbi阿萨德吧上课的按时等不及哈巴三大";
            writer.write(s, 0, 5);
​
            // 刷新数据到文件中
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

复制文本(基于字符流)

public class FileReadWriterCopy {
    public static void main(String[] args) {
        // 通过字符流实现文件的拷贝
        try (
                FileReader reader = new FileReader("day09\src\itheima\d1_char_stream\doupo.txt");
                FileWriter writer = new FileWriter("day09\src\itheima\d1_char_stream\doupo_copy.txt");
        ) {
            char[] buffer = new char[1024];
            int len;
            while ((len = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
​

字节缓冲流

public class BufferedInputStreamTest1 {
    public static void main(String[] args) {
        // 使用字节缓冲流复制文件
        FileInputStream is = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            is = new FileInputStream("day09\src\itheima\d2_buffered_stream\cat.jpg");
            // 用字节缓冲输入流,包装字节输入流
            bis = new BufferedInputStream(is);
​
            fos = new FileOutputStream("day09\src\itheima\d2_buffered_stream\cat_copy.jpg");
            // 用字节缓冲输出流,包装字节输出流
            bos = new BufferedOutputStream(fos);
​
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 先关哪个?先关包在外面的(一层一层关闭)
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
​
        }
​
​
    }
}

字符缓冲流

public class BufferedReaderTest2 {
    public static void main(String[] args) {
        try (
                // 掌握字符缓冲输入流的用法。
                FileReader reader = new FileReader("day09\src\itheima\d2_buffered_stream\doupo.txt");
                BufferedReader br = new BufferedReader(reader);
        ) {
​
            /*
            经典写法:一次读1024个字符
        char[] buffer = new char[1024];
        int len;
        while ((len = br.read(buffer)) != -1) {
            String s = new String(buffer, 0, len);
            System.out.println(s);
        }*/
            // BufferedReader独有方法:一次读一行
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
​
        } catch (Exception e) {
            e.printStackTrace();
        }
​
​
    }
}
public class BufferedWriterTest3 {
    public static void main(String[] args) {
        // 掌握字符缓冲输出流的用法。
        try (
                // 创建字符输出流
                FileWriter writer = new FileWriter("day09\src\itheima\d2_buffered_stream\doupo01.txt", true);
                // 创建字符缓冲输出流
                BufferedWriter bw = new BufferedWriter(writer);
        ) {
            bw.write(",有一个小镇青年,叫萧炎");
            // 换行方法
            bw.newLine();
            bw.write("后续内容收费");
​
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
​
    }
}

转换输入流

public class InputStreamReaderTest1 {
    public static void main(String[] args) {
        try (
                // 乱码代码演示:文件编码格式是GBK,而默认读取文件编码格式为UTF-8
​
                // 创建字节文件输入流
                FileInputStream is = new FileInputStream("day09\src\itheima\d3_transform_stream\panlong.txt");
                // 创建输入转换流
                InputStreamReader isr = new InputStreamReader(is,"GBK");
                // 把字符输入转换流放入新建的缓冲流中
                BufferedReader br = new BufferedReader(isr);
        ) {
​
            String s;
            while ((s = br.readLine()) != null) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
​
    }
}

转换输出流

public class InputStreamReaderTest2 {
    public static void main(String[] args) throws IOException {
        try (
                // 掌握字符输入转换流的作用。
​
                // 创建一个文件字节输出流
                FileOutputStream fos = new FileOutputStream("day09\src\itheima\d3_transform_stream\panlong.txt", true);
                // 把原始的字节输出流,按照指定的字符集编码转换成字符输出转换流(避免乱码)
                OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
                // 把字符输出转换流包装成缓冲字符输出流(效率更高)
                BufferedWriter bw = new BufferedWriter(osw);
        ) {
​
            bw.write(",刹那间,村门口来了一位穿着背带裤的青年,发出桀桀桀的声音");
​
        } catch (Exception e) {
            e.printStackTrace();
        }
​
    }
}

序列化流

对象
// 一个类实现了Serializable接口,就有序列化的能力
public class User implements Serializable {
​
    // 不写,默认会生成一个,表示类的序列化版本
    private static final long serialVersionUID = -5294956369762487124L;
​
    private String loginName;
    // transient:指定变量不会被序列化到文件中
    private transient String password;
    private String userName;
    private int age;
}
​
​
​
输出
​
public class Test1ObjectOutputStream {
    public static void main(String[] args) {
        // 掌握对象字节输出流的使用:序列化对象。
​
        try (
                // 创建序列化输出流
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day09\src\itheima\d6_object_stream\user.txt"));
        ) {
            User user = new User("root", "123456", "张三", 18);
            System.out.println(user);
​
            // writeObject方法:写入对象
            oos.writeObject(user);
​
        } catch (Exception e) {
            e.printStackTrace();
        }
​
​
    }
}
​
​
读取
​
public class Test2ObjectInputStream {
    public static void main(String[] args) {
        // 掌握对象字节输入流的使用:反序列化对象。
​
        ObjectInputStream dis = null;
        try {
            dis = new ObjectInputStream(new FileInputStream("day09\src\itheima\d6_object_stream\user.txt"));
​
            User user = (User) dis.readObject();
            user.setAge(100);
            System.out.println(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(dis);
        }
    }
}
​

CommonsIO

package itheima.d7_commons_io;
​
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
​
import java.io.File;
import java.io.IOException;
​
/**
 * 目标:使用CommonsIO框架进行IO相关的操作。
 */
public class CommonsIOTest1 {
    public static void main(String[] args) throws IOException {
        // 使用CommonsIO框架进行IO相关的操作。
​
        // FileUtils
​
        // 文件拷贝
        FileUtils.copyFile(new File("day09\src\itheima\d7_commons_io\cat.jpg"), new File("day09\src\itheima\d7_commons_io\cat_copy.jpg"));
​
        // 拷贝目录
        FileUtils.copyDirectory(new File("day09\src\itheima\d7_commons_io\d1"), new File("day09\src\itheima\d7_commons_io\d1_copy"));
​
        // 删除目录
        FileUtils.deleteDirectory(new File("day09\src\itheima\d7_commons_io\d1_copy"));
​
        // IOUtils.closeQuietly:优雅的关闭流。参数是可变参数,把最外层的包装流传进去就行
        IOUtils.closeQuietly();
​
    }
}