Java IO流案例如何基础实操

wen java案例 19

本文目录导读:

Java IO流案例如何基础实操

  1. 文件字节流操作(最基础)
  2. 字符流操作(处理文本文件)
  3. 综合案例:配置文件读写
  4. 对象序列化
  5. 实际项目工具类
  6. 关键知识点总结

我来给你一个从基础到入门的Java IO流实操指南,包含最常用的几个案例。

文件字节流操作(最基础)

1 文件复制(字节流)

import java.io.*;
public class FileCopyDemo {
    public static void main(String[] args) {
        // 源文件和目标文件路径
        String sourceFile = "D:/test/source.txt";
        String destFile = "D:/test/dest.txt";
        // 使用try-with-resources自动关闭流
        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(destFile)) {
            byte[] buffer = new byte[1024]; // 1KB缓冲区
            int bytesRead;
            // 读取数据并写入
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("文件复制完成!");
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO异常:" + e.getMessage());
        }
    }
}

字符流操作(处理文本文件)

1 读取文本文件

import java.io.*;
public class TextFileReader {
    public static void main(String[] args) {
        String filePath = "D:/test/input.txt";
        try (FileReader fr = new FileReader(filePath);
             BufferedReader br = new BufferedReader(fr)) {
            String line;
            int lineNumber = 0;
            // 逐行读取
            while ((line = br.readLine()) != null) {
                lineNumber++;
                System.out.println("第" + lineNumber + "行: " + line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2 写入文本文件

import java.io.*;
public class TextFileWriter {
    public static void main(String[] args) {
        String filePath = "D:/test/output.txt";
        String[] content = {
            "第一行内容",
            "第二行内容",
            "第三行内容"
        };
        try (FileWriter fw = new FileWriter(filePath, false); // false=覆盖, true=追加
             BufferedWriter bw = new BufferedWriter(fw)) {
            for (String line : content) {
                bw.write(line);
                bw.newLine(); // 换行
            }
            // 手动刷新缓冲区
            bw.flush();
            System.out.println("写入完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

综合案例:配置文件读写

import java.io.*;
import java.util.Properties;
public class ConfigManager {
    // 写入配置
    public void saveConfig(String filePath) {
        Properties prop = new Properties();
        // 设置配置项
        prop.setProperty("server.port", "8080");
        prop.setProperty("server.host", "localhost");
        prop.setProperty("db.username", "admin");
        prop.setProperty("db.password", "123456");
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            // 保存到文件
            prop.store(fos, "Server Configuration");
            System.out.println("配置保存成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 读取配置
    public void loadConfig(String filePath) {
        Properties prop = new Properties();
        try (FileInputStream fis = new FileInputStream(filePath)) {
            // 从文件加载配置
            prop.load(fis);
            // 读取配置项
            String port = prop.getProperty("server.port");
            String host = prop.getProperty("server.host");
            String username = prop.getProperty("db.username");
            System.out.println("服务器配置:");
            System.out.println("端口: " + port);
            System.out.println("主机: " + host);
            System.out.println("用户名: " + username);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        ConfigManager cm = new ConfigManager();
        String configFile = "D:/test/config.properties";
        // 保存配置
        cm.saveConfig(configFile);
        // 读取配置
        cm.loadConfig(configFile);
    }
}

对象序列化

import java.io.*;
// 需要序列化的类必须实现Serializable接口
class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private transient String password; // transient关键字表示不序列化
    public Student(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }
    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + ", password='" + password + "'}";
    }
}
public class ObjectIODemo {
    // 序列化对象到文件
    public void serializeObject(String filePath, Student student) {
        try (FileOutputStream fos = new FileOutputStream(filePath);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(student);
            System.out.println("对象序列化成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 从文件反序列化对象
    public Student deserializeObject(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            Student student = (Student) ois.readObject();
            return student;
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args) {
        ObjectIODemo demo = new ObjectIODemo();
        String filePath = "D:/test/student.dat";
        // 创建对象并序列化
        Student stu = new Student("张三", 20, "secret123");
        demo.serializeObject(filePath, stu);
        // 反序列化
        Student stuLoaded = demo.deserializeObject(filePath);
        if (stuLoaded != null) {
            System.out.println("反序列化结果: " + stuLoaded);
        }
    }
}

实际项目工具类

import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
    /**
     * 读取文本文件所有行
     */
    public static List<String> readLines(String filePath) {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }
    /**
     * 写入字符串列表到文件
     */
    public static void writeLines(String filePath, List<String> lines) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 复制文件
     */
    public static void copyFile(String sourcePath, String destPath) {
        try (FileInputStream fis = new FileInputStream(sourcePath);
             FileOutputStream fos = new FileOutputStream(destPath)) {
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 读取文件内容为字符串
     */
    public static String readFileAsString(String filePath) {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }
    public static void main(String[] args) {
        // 测试工具类
        String testFile = "D:/test/test.txt";
        // 写入测试数据
        List<String> data = new ArrayList<>();
        data.add("Hello");
        data.add("World");
        data.add("Java IO");
        writeLines(testFile, data);
        // 读取测试数据
        List<String> readData = readLines(testFile);
        System.out.println("读取的数据: " + readData);
    }
}

关键知识点总结

  1. 字节流 vs 字符流

    • 字节流:处理二进制文件(图片、视频等)
    • 字符流:处理文本文件(.txt, .xml等)
  2. 缓冲流的作用

    • 提高读写效率
    • 减少物理IO次数
  3. try-with-resources

    • 自动关闭流资源
    • 代码更简洁
  4. 常见注意事项

    • 用完必须关流
    • 字符编码要统一
    • 缓冲区大小选择(4KB-8KB较合适)

这些案例覆盖了日常开发中最常用的IO操作场景,建议动手实践每个案例,加深理解。

抱歉,评论功能暂时关闭!