Java的IO学习目录

Java的IO学习目录

一、Java IO 基础概念

1. IO 流的概念与分类

  • 输入流 vs 输出流
    • 输入流(InputStream/Reader):从数据源读取数据(如文件、网络)
    • 输出流(OutputStream/Writer):向目标写入数据(如文件、控制台)
  • 字节流 vs 字符流
    • 字节流(InputStream/OutputStream):处理二进制数据(图片、音频等)
    • 字符流(Reader/Writer):处理文本数据(.txt, .csv 等)
  • 节点流 vs 处理流
    • 节点流(FileInputStream, FileReader):直接操作数据源
    • 处理流(BufferedInputStream, BufferedReader):包装节点流,提供额外功能(缓冲、转换等)

二、字节流操作

1. 文件字节流

import java.io.*;

public class FileByteStreamExample {
    public static void main(String[] args) {
        String filePath = "test.txt";
        
        // 写入文件
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write("Hello, Java IO!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取文件
        try (FileInputStream fis = new FileInputStream(filePath)) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 缓冲字节流(提高性能)

import java.io.*;

public class BufferedByteStreamExample {
    public static void main(String[] args) {
        String filePath = "test.txt";

        // 写入(缓冲)
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
            bos.write("Buffered IO is faster!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取(缓冲)
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            int data;
            while ((data = bis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 数据字节流(读写基本数据类型)

import java.io.*;

public class DataStreamExample {
    public static void main(String[] args) {
        String filePath = "data.dat";

        // 写入 int, double, boolean
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(filePath))) {
            dos.writeInt(100);
            dos.writeDouble(3.14);
            dos.writeBoolean(true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取
        try (DataInputStream dis = new DataInputStream(new FileInputStream(filePath))) {
            System.out.println(dis.readInt());      // 100
            System.out.println(dis.readDouble());   // 3.14
            System.out.println(dis.readBoolean());  // true
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

三、字符流操作

1. 文件字符流

import java.io.*;

public class FileCharStreamExample {
    public static void main(String[] args) {
        String filePath = "text.txt";

        // 写入(字符流)
        try (FileWriter fw = new FileWriter(filePath)) {
            fw.write("Hello, 字符流!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取(字符流)
        try (FileReader fr = new FileReader(filePath)) {
            int data;
            while ((data = fr.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 缓冲字符流(逐行读取)

import java.io.*;

public class BufferedCharStreamExample {
    public static void main(String[] args) {
        String filePath = "text.txt";

        // 写入(缓冲)
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {
            bw.write("第一行");
            bw.newLine();
            bw.write("第二行");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取(逐行)
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 转换流(处理编码问题)

import java.io.*;

public class ConvertStreamExample {
    public static void main(String[] args) {
        String filePath = "text_gbk.txt";
        String charset = "GBK"; // 处理中文编码问题

        // 写入(GBK 编码)
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charset)) {
            osw.write("中文测试");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取(GBK 解码)
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), charset)) {
            int data;
            while ((data = isr.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

四、标准 IO 与重定向

1. 标准输入输出流

import java.util.Scanner;

public class StandardIOExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入内容:");
        String input = scanner.nextLine();
        System.out.println("你输入的是:" + input);
    }
}

2. 重定向(System.setOut)

import java.io.*;

public class RedirectExample {
    public static void main(String[] args) throws FileNotFoundException {
        // 把 System.out 重定向到文件
        PrintStream fileOut = new PrintStream("output.txt");
        System.setOut(fileOut);

        System.out.println("这行内容会被写入文件,而不是控制台!");
    }
}

五、文件与目录操作

1. File 类(文件/目录操作)

import java.io.File;

public class FileOperationExample {
    public static void main(String[] args) {
        File file = new File("test.txt");

        // 检查文件是否存在
        System.out.println("文件是否存在?" + file.exists());

        // 创建文件
        try {
            if (!file.exists()) {
                file.createNewFile();
                System.out.println("文件已创建!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 删除文件
        if (file.delete()) {
            System.out.println("文件已删除!");
        }
    }
}

2. 文件过滤器

import java.io.File;
import java.io.FilenameFilter;

public class FileFilterExample {
    public static void main(String[] args) {
        File dir = new File(".");

        // 只列出 .txt 文件
        String[] txtFiles = dir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        });

        for (String file : txtFiles) {
            System.out.println(file);
        }
    }
}

六、对象序列化

1. 基本序列化

import java.io.*;

class Person implements Serializable {
    String name;
    int age;

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

public class SerializationExample {
    public static void main(String[] args) {
        Person person = new Person("张三", 25);
        String filePath = "person.dat";

        // 序列化(写入对象)
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            oos.writeObject(person);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化(读取对象)
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
            Person loadedPerson = (Person) ois.readObject();
            System.out.println(loadedPerson.name + ", " + loadedPerson.age);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

七、NIO 基础

1. Files 和 Path(Java NIO 2)

import java.nio.file.*;
import java.util.List;

public class NIOExample {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("test.txt");

        // 写入文件
        Files.write(path, "Hello, NIO!".getBytes());

        // 读取文件
        List<String> lines = Files.readAllLines(path);
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

八、IO 最佳实践

1. try-with-resources(自动关闭流)

import java.io.*;

public class TryWithResourcesExample {
    public static void main(String[] args) {
        // Java 7+ 自动关闭流
        try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 大文件处理(避免内存溢出)

import java.io.*;

public class LargeFileExample {
    public static void main(String[] args) {
        String inputFile = "large_file.txt";
        String outputFile = "output.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(inputFile));
             BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

九、高级主题

1. 压缩流(Zip 文件处理)

import java.io.*;
import java.util.zip.*;

public class ZipExample {
    public static void main(String[] args) throws IOException {
        // 压缩文件
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("archive.zip"))) {
            zos.putNextEntry(new ZipEntry("file1.txt"));
            zos.write("Hello, Zip!".getBytes());
            zos.closeEntry();
        }

        // 解压文件
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream("archive.zip"))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                System.out.println("文件名: " + entry.getName());
                int data;
                while ((data = zis.read()) != -1) {
                    System.out.print((char) data);
                }
            }
        }
    }
}

十、实战项目

1. 文件加密/解密工具(XOR 简单加密)

import java.io.*;

public class FileEncryptor {
    public static void encryptFile(String inputFile, String outputFile, int key) throws IOException {
        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(outputFile)) {
            int data;
            while ((data = fis.read()) != -1) {
                fos.write(data ^ key); // XOR 加密
            }
        }
    }

    public static void main(String[] args) throws IOException {
        encryptFile("plain.txt", "encrypted.dat", 123);
        encryptFile("encrypted.dat", "decrypted.txt", 123); // 解密
    }
}

总结

  • 字节流InputStream/OutputStream(二进制数据)
  • 字符流Reader/Writer(文本数据)
  • 缓冲流BufferedInputStream/BufferedReader(提高性能)
  • 对象序列化ObjectInputStream/ObjectOutputStream
  • NIOFilesPath(更高效的文件操作)
  • 最佳实践try-with-resources、大文件处理

这个目录涵盖了 Java IO 的核心知识点,并提供了完整的代码示例,适合从入门到进阶学习! 🚀

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值