IO流(java)

本文详细介绍了Java中文件的创建、读写、复制,以及各种流(如FileInputStream、FileOutputStream、FileReader、FileWriter、BufferedReader、BufferedWriter)的使用方法,还包括对象序列化和处理乱码的解决方案。
摘要由CSDN通过智能技术生成

-----------------韩顺平Java笔记

创建文件

Java创建文件有三种方式。

方法一 new File(String filename)  //根据路径创建文件

方法二: new File(File parent, String child) // 根据父目录文件+子路径构建

方法三: new File(String parent, String child) // 根据父目录和子路径创建

    // 方法一 new File(String filename)  //根据路径创建文件
    @Test
    public void fileCreat(){
        String filePath = "E:\\file01.txt";
        File file = new File(filePath);

        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 方法二: new File(File parent, String child) // 根据父目录文件+子路径构建
    @Test
    public void fileCreat2(){
        File parentFile = new File("E:\\");
        String filePath = "file02.txt";
        File file = new File(parentFile, filePath);

        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 方法三: new File(String parent, String child) // 根据父目录和子路径创建
    @Test
    public void creatFile3(){
        String parentPath = "E:\\";
        String childPath = "file03.txt";
        File file = new File(parentPath, childPath);

        try {
            file.createNewFile();
            System.out.println("创建成功~");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

FileInputStream

@Test
    public void readFile01(){
        String filePath = "E:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            // 创建FileInputStream 对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            // 从该输入流读取一个字节的数据,
            // 如果返回-1, 表示读取完毕
            while ((readData = fileInputStream.read()) != -1){
                System.out.print((char)readData); // 转成char显示
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // 一次读入多个字节的方法
    @Test
    public void readFile02(){
        String filePath = "E:\\hello.txt";
        int readlen = 0;
        FileInputStream fileInputStream = null;
        byte[] buf = new byte[8];
        try {
            // 创建FileInputStream 对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            // 从该输入流读取8个字节的数据,
            // 如果返回-1, 表示读取完毕
            while ((readlen = fileInputStream.read(buf)) != -1){ //
                System.out.print(new String(buf, 0, readlen)); // 转成char显示
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

FileOutputStream

 /**
     * FileOutputStream. 将数据写到文件中
     * 若文件不存在,则创建
     */
    @Test
    public void writerFile(){
        String filePath = "E:\\writer.txt";
        FileOutputStream fileOutputStream = null;

        try {
            // new FileOutputStream(filePath)创建方式,当写入内容时,会覆盖之前的内容
            // new FileOutputStream(filePath, true)创建方式,当写入内容时,会从之前内容的尾部开始写入
            fileOutputStream = new FileOutputStream(filePath, true);
            // 写入一个字节
            // fileOutputStream.write('G');
            // 写入字符串
            String str = "hello, word";
            // getBytes() 可以把字符串转换为字节数组
            fileOutputStream.write(str.getBytes());
            // fileOutputStream.write(byte[], off, len); 写入方式,会从byte[]索引off写入len个字节
            fileOutputStream.write(str.getBytes(), 2, 3);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

文件拷贝

/**
     * 将文件从一个地方拷贝到另一个地方
     * 思路分析: 先用FileInputStream将文件读入到程序中
     * 在用FileOutputStream将程序的数据输入到文件
     */
    @Test
    public void fileCopy(){
        String fileReadPath = "E:\\dog.jfif";
        String fileWritePath = "E:\\dog1.png";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        byte[] buf = new byte[1024];
        int readLen = 0;

        try {
            fileInputStream = new FileInputStream(fileReadPath);
            fileOutputStream = new FileOutputStream(fileWritePath);
            while ((readLen = fileInputStream.read(buf)) != -1){
                fileOutputStream.write(buf, 0, readLen);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
                if (fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

FileReader

/**
     * 单个字符读取
     */
    @Test
    public void FileRead(){
        String filePath = "E:\\file02.txt";
        FileReader fileReader = null;
        int readLen = 0;

        try {
            fileReader = new FileReader(filePath);
            while((readLen = fileReader.read()) != -1){
                System.out.print((char) readLen);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 多个字符读取
     */
    @Test
    public void FileRead01(){
        String filePath = "E:\\file02.txt";
        FileReader fileReader = null;
        int readLen = 0;
        char[] buf = new char[8];
        try {
            fileReader = new FileReader(filePath);
            // 循环读取,使用read(buf),返回的是实际读取到的字符数
            // 如果返回-1,说明读取结束
            while((readLen = fileReader.read(buf)) != -1){
                System.out.print(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

FileWriter

 @Test
    public void FileWriter(){
        String filePath = "E:\\file03.txt";
        java.io.FileWriter fileWriter = null;
        int len = 0;
        char[] c = {'q', 'w', 'e'};
        try {
            fileWriter = new java.io.FileWriter(filePath);
            // writer( int ) 写入单个字符
            fileWriter.write('H');
            // writer( char[] ) 写入指定数组
            fileWriter.write(c);
            // writer( char[], off, len) 写入指定数组的指定部分
            fileWriter.write("王**拯救世界".toCharArray(), 3, 4);
            // writer( String ) 写入指定字符串
            fileWriter.write("王**");
            // writer( String, off, len ) 写入指定字符串的指定部分
            fileWriter.write("铠甲变身", 2, 2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 一定要 关闭文件或者刷新文件,否则没写进去
            try {
                fileWriter.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

节点流和处理流

BufferedReader

    @Test
    public void BufferedReader_() throws IOException {
        String filePath = "E:\\file02.txt";
        String str;
        java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new                     FileReader(filePath));
        while ((str = bufferedReader.readLine()) != null){
            System.out.println(str);
        }
        bufferedReader.close();

BufferedWriter

public void BufferedWriter_() throws IOException {
        String filePath = "E:\\file04.txt";
        java.io.BufferedWriter bufferedWriter = new java.io.BufferedWriter(new FileWriter(filePath, true));
        bufferedWriter.write("王**宇宙之王");
        bufferedWriter.newLine();
        bufferedWriter.write("王**宇宙之王");
        bufferedWriter.newLine();
        bufferedWriter.write("王**宇宙之王");
        bufferedWriter.close();
    }

Buffered拷贝

思路同之前拷贝相同

对象处理流

public class ObjectOutputStream {
    public static void main(String[] args) {

    }
    @Test
    /**
     * 1.序列化:就是在保存数据时,保存数据的值和数据类型
     * 2.反序列化:就是在回复数据时,回复数据的值和数据类型
     * 3.需要让某个对象支持序列化机制,必须让其类是可序列化的,为了让某类可序列化,该类必须实现如下两个接口之一
     *      (1)Serializable // 这是一个标记接口,没有方法
     *      (2)Externalizable // 该接口有方法需要实现
     */
    public void ObjectOutputStream_() throws Exception {
        // 序列化后,保存的文件不是文本文件,而是按照它的格式
        String filePath = "E:\\data.dat";
        java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(new FileOutputStream(filePath));

        oos.writeInt(100); // int --> Integer (int自动装箱为Integer,并且Integer已经实现了Serializable)
        oos.writeBoolean(true); // boolean -->Boolean(实现了Serializable)
        oos.writeChar('a'); // char --> Character(实现了Serializable)
        oos.writeDouble(2.5); // double --> Double(实现了Serializable)
        oos.writeUTF("王大帝"); //String
        oos.writeObject(new Dog("大黄", 2));

        oos.close();
    }
}

class Dog implements Serializable {
    String name;
    int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

反序列化

 对象处理流细节

标准输入输出流

乱码引出转换流

问题:

public static void main(String[] args) throws IOException {
        // 1. 创建字符出入流BufferedReader [处理流]
        // 2. 读取文件“file01.txt”
        // 3. 默认情况下,是按照utf-8编码(若是其他编码,则可能造成乱码)
        String filePath = "E:\\file01.txt";
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String s = reader.readLine();
        System.out.println("读到的内容: " + s);
        reader.close();
    }

解决:

/**
 * 演示使用InputStreamReader解决中文乱码问题
 * 将字节流FileInputStream转成 字符流 InputStreamReader, 指定编码
 */
public class InputStreamReader {
    public static void main(String[] args) throws IOException {
        String filePath = "E:\\file01.txt";
        // 1. 把 FileInputStream 转为 InputStreamReader
        // 2. 指定编码
        java.io.InputStreamReader gbk = new java.io.InputStreamReader(new FileInputStream(filePath), "gbk");
        // 3. 把InputStreamReader传入 BufferedReader
        BufferedReader reader = new BufferedReader(gbk);
        // 4. 读取
        String str = reader.readLine();
        System.out.println("读取:" + str);
        // 5. 关闭外层流
        reader.close();
    }
}
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        // 编程将字节流FileOutputStream包装成(转换成)字符流OutputStreamWriter,对文件进行写入,可指定编码格式
        String filePath = "E:\\wxl.txt";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), "gbk");
        String s = "王**宇宙之神";
        osw.write(s);
        osw.close();
        System.out.println("按照gbk格式保存成功~");
    }
}

properties

常见方法:

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值