chengaofeng
发布于 2024-09-18 / 7 阅读
0
0

Java IO文件的读取与写入

File类

  1. File类是java.io包下代表与平台无关的文件和目录

  2. 程序中操作文件和目录,都可以通过File类来完成,File能新建、删除、重命名文件和目录

  3. File类并不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流

package cn.chengaofeng.io;

import java.io.File;
import java.io.IOException;

import org.junit.Test;

public class FileTest {
    @Test
    public void testFile() throws IOException {
        File file = new File("./test.txt");
        File dir = new File("./test");
        boolean bool = file.createNewFile();
        System.out.println(bool);
        System.out.println("是否存在:" + file.exists());
        System.out.println("是否是目录:" + file.isDirectory());
        System.out.println("是否是文件:" + file.isFile());
        System.out.println("是否可读:" + file.canRead());
        System.out.println("是否可写:" + file.canWrite());
        System.out.println("是否隐藏:" + file.isHidden());
        System.out.println("文件长度:" + file.length());
        System.out.println("文件最后修改时间:" + file.lastModified());
        System.out.println("文件绝对路径:" + file.getAbsolutePath());
        System.out.println("文件相对路径:" + file.getPath());
        System.out.println("文件名称:" + file.getName());
        System.out.println("文件父目录:" + file.getParent());
        System.out.println("文件父目录File对象:" + file.getParentFile());
        System.out.println("删除文件是否成功:" + file.delete());

        boolean bool2 = dir.mkdir();
        System.out.println(bool2);
        System.out.println("是否存在:" + dir.exists());
        System.out.println("是否是目录:" + dir.isDirectory());
        System.out.println("是否是文件:" + dir.isFile());
        System.out.println("是否可读:" + dir.canRead());
        System.out.println("是否可写:" + dir.canWrite());
        System.out.println("是否隐藏:" + dir.isHidden());
        System.out.println("文件长度:" + dir.length());
        System.out.println("文件最后修改时间:" + dir.lastModified());
        System.out.println("文件绝对路径:" + dir.getAbsolutePath());
        System.out.println("文件相对路径:" + dir.getPath());
        System.out.println("文件名称:" + dir.getName());
        System.out.println("文件父目录:" + dir.getParent());
        System.out.println("文件父目录File对象:" + dir.getParentFile());
        System.out.println("删除目录是否成功:" + dir.delete());
    }
}

字节字符流实现文件读取与写入

流-Stream

Java把传输的数据抽象成流的概念,就像河流一样,从一个地方流到另一个地方,简化了程序处理。

java.io包

  1. Java的IO通过java.io包下的类和接口来支持

  2. 按出入的方向可分为:输入与输出

  3. 按内容类型可分为:字节流与字符流

四种抽象类

  1. 字节输入流-InputStream

  2. 字节输出流-OutputStream

  3. 字符输入流-Reader

  4. 字符输出流-Writer

字节输入流-InputStream

  1. InputStream是所有字节输入流的父类

  2. InputStream提供核心方法read(),用于读取字节数据

  3. FileInputStream类专用于读取二进制文件

InputStream通用开发模式

  1. 实例代InputStream对象

  2. 利用read方法循环读取字节数据,并进行处理

  3. 调用close方法关半InputStream对象

package cn.chengaofeng.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

public class FileCopyTest {
    @Test
    public void run() throws FileNotFoundException, IOException {
        File source = new File("./pom.xml");
        InputStream in = new FileInputStream(source);
        byte[] bs = new byte[1024];
        int len;
        while ((len = in.read(bs)) != -1) {
            System.out.println(new String(bs, 0, len));
        }
        in.close();

        // try-with-resources
        // try (InputStream in = new FileInputStream(source)) {
        // byte[] bs = new byte[1024];
        // int len;
        // while ((len = in.read(bs)) != -1) {
        // System.out.println(new String(bs, 0, len));
        // }
        // }
    }
}

字节输出流-OutputStream

  1. OutputStream是所有字节输出流的父类

  2. OutputStream提供核心方法write(),用于向指定输出流输出字节数组

  3. FileOutputStream类专用于写入二进制文件

OutputStream通用开发模式

  1. 实例化OutputStream对象

  2. 利用write方法循环写入字节数据

  3. 调用close方法关闭OutputStream对象

package cn.chengaofeng.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.junit.Test;

public class FileCopyTest {
    @Test
    public void run() throws FileNotFoundException, IOException {
        File source = new File("./pom.xml");
        File target = new File("./pom-copy.xml");
        InputStream in = new FileInputStream(source);
        OutputStream out = new FileOutputStream(target);
        byte[] bs = new byte[1024];
        int len;
        while ((len = in.read(bs)) != -1) {
            System.out.println(new String(bs, 0, len));
            out.write(bs, 0, len);
        }
        out.close();
        in.close();

        // try-with-resources
        // try (InputStream in = new FileInputStream(source)) {
        // byte[] bs = new byte[1024];
        // int len;
        // while ((len = in.read(bs)) != -1) {
        // System.out.println(new String(bs, 0, len));
        // }
        // }
    }
}

字符输入流-Reader 和 字符输出流-Writer

  1. Reader是所有字符输入流的抽象父类

  2. Writer是所有字符输出流的抽象父类

  3. FileReader与FileWriter分别对应了文本文件的读取与写入

package cn.chengaofeng.io;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;

import org.junit.Test;

public class TextTest {
    @Test
    public void testText() {
        // 1. 创建文件对象
        File file = new File("./test.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 2. 创建字符输出流
        try (FileWriter writer = new FileWriter(file)) {
            // 3. 写入数据
            writer.write("Hello, World!");
            // 4. 追加数据
            writer.append("Hello, World!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取文件
        // 1. 创建字符输入流
        try (Reader reader = new FileReader(file)) {
            // 2. 读取数据
            char[] cs = new char[1024];
            int len;
            while ((len = reader.read(cs)) != -1) {
                System.out.println(new String(cs, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

字节流与字符流的转换

  1. 输入/输出流体系中还提供了两个转换流,用于实现将字节流转换成字符流

  2. InputStreamReader将字节输入流转换成字符输入流

  3. OutputStreamWriter将字节输出流转换成字符输出流

  4. 没有提供字符输入流转为字节输入流

  5. 实际开发中使用上面的FileReader和FileWriter即可,这两个类就是继承自InputStreamReader和OutputStreamWriter

    @Test
    public void testInputStreamReader() throws FileNotFoundException {
        // 1. 创建文件对象
        File file = new File("./test.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            try (FileInputStream fis = new FileInputStream(file)) {
                // 需要确保能转换为字符才能使用InputStreamReader
                InputStreamReader in = new InputStreamReader(fis, "UTF-8");
                while (in.ready()) {
                    System.out.print((char) in.read());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    @Test
    public void testInputStreamReader() throws FileNotFoundException {
        // 1. 创建文件对象
        File file = new File("./test.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (FileInputStream fis = new FileInputStream(file)) {
            // 需要确保能转换为字符才能使用InputStreamReader
            InputStreamReader in = new InputStreamReader(fis, "UTF-8");
            StringBuffer sb = new StringBuffer();
            while (in.ready()) {
                sb.append((char) in.read());
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

缓冲区

缓冲区的作用

  1. 默认文件的读取与写入都是逐个字节/字符完成的,但这种处理方式并不高效,如果将读取或写入的数据整块在内存中缓存,一次性批量读取、写入、便可以有效提高数据交互效率

  2. BufferedInputStream与BufferedOutputStream用于缓冲字节输入、输出流

  3. BufferedReader与BufferedWriter用于缓冲字符输入、输出流

一行一行读文本

package cn.chengaofeng.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import org.junit.Test;

public class BufferedTest {

    @Test
    public void run() throws FileNotFoundException, IOException {
        File file = new File("./pom.xml");
        Reader reader = new FileReader(file);
        try (BufferedReader br = new BufferedReader(reader)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

其他常用I/O流

ByteArrayInputStream-字节数组输入流

ByteArrayOutputStream-字节数组输出流

CharArrayReader-字符数组字符输入流

CharArrayWriter-字符数组字符输出流

ObjectInputStream-对象输入字节流

ObjectOutputStream-对象输出字节流

PrintStream-打印字节输出流

PrintWriter-打印字符输出流


评论