Java 文件读写示例:使用 FileOutputStream 和 FileInputStream

本示例演示了如何在 Java 中使用 FileOutputStreamFileInputStream 进行文件写入和读取,并使用 UTF-8 编码避免乱码问题。

写入文件

public static void fileout() throws FileNotFoundException {
    File file = new File('D:/file2/result2.txt');
    FileOutputStream out = new FileOutputStream(file);
    String str = '小明-18-90;小红-17-95;老刚-29-60';
    try {
        out.write(str.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

读取文件

public static void filein() throws FileNotFoundException {
    File file = new File('D:/file2/result2.txt');
    FileInputStream in = new FileInputStream(file);
    try {
        int size = in.available();
        byte[] buffer = new byte[size];
        in.read(buffer);
        String str = new String(buffer, 'UTF-8');
        System.out.println(str);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

解释:

  • 写入文件:
    • 使用 FileOutputStream 创建一个输出流,并将数据写入到文件中。
    • 使用 str.getBytes() 将字符串转换为字节数组,并使用 out.write() 将字节数组写入到文件中。
    • 使用 out.close() 关闭输出流,释放资源。
  • 读取文件:
    • 使用 FileInputStream 创建一个输入流,从文件中读取数据。
    • 使用 in.available() 获取文件大小,并使用 byte[] buffer 存储读取到的字节数据。
    • 使用 in.read(buffer) 将文件内容读取到字节数组中。
    • 使用 new String(buffer, 'UTF-8') 将字节数组转换为字符串,并指定编码为 UTF-8,避免出现乱码问题。
    • 使用 in.close() 关闭输入流,释放资源。

注意事项:

  • 文件路径应该根据实际情况进行修改。
  • 使用 UTF-8 编码可以避免中文乱码问题。
  • 记得使用 try...catch...finally 块来处理异常,确保程序的健壮性。

更多内容:

Java 文件读写示例:使用 FileOutputStream 和 FileInputStream

原文地址: https://www.cveoy.top/t/topic/p7ru 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录