You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java导出文件为ANSI格式而非UTF-8的问题求助

问题根源与解决方案

嘿,我懂你现在的困惑——你一直在调IDE的字符编码设置,但根本问题出在你用错了IO工具类上!

你当前用的ObjectOutputStream是用来序列化Java对象的,它输出的不是普通文本,而是Java专用的二进制序列化数据。所以你用文本编辑器打开时,看到的那种类似ANSI乱码的内容完全是正常现象,这和IDE的字符编码设置一点关系都没有。

两种解决方向,看你的需求:

1. 我想把对象内容写成可读的文本文件

那别再用ObjectOutputStream了,改用处理文本的IO类,比如OutputStreamWriter(还能指定编码)或者BufferedWriter。给你改个示例代码:

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

class Student {
    int id;
    String name;
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class WriteStudentToText {
    public static void main(String args[]){
        try{
            Student s1 = new Student(211,"ravi");
            // 用OutputStreamWriter写入文本,明确指定UTF-8编码
            FileOutputStream fout = new FileOutputStream("f.txt");
            OutputStreamWriter writer = new OutputStreamWriter(fout, StandardCharsets.UTF_8);
            // 把对象属性拼接成可读的文本内容
            writer.write(String.format("ID: %d, Name: %s", s1.id, s1.name));
            writer.flush();
            writer.close();
            System.out.println("success");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

运行后打开f.txt,就能看到正常的可读文本了。

2. 我确实需要序列化对象(之后要再读回来用)

那你当前的代码完全没问题!生成的二进制文件是正确的序列化格式,只是文本编辑器读不懂而已。之后要读取这个对象时,用ObjectInputStream就能正常解析,示例代码如下:

import java.io.FileInputStream;
import java.io.ObjectInputStream;

class Student implements Serializable{
    int id;
    String name;
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class ReadSerializedStudent {
    public static void main(String args[]){
        try{
            FileInputStream fin = new FileInputStream("f.txt");
            ObjectInputStream in = new ObjectInputStream(fin);
            // 反序列化得到Student对象
            Student s1 = (Student)in.readObject();
            System.out.println("读取到的对象:ID=" + s1.id + ", Name=" + s1.name);
            in.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

运行这段代码,就能正确还原你之前写入的Student对象了。


内容的提问来源于stack exchange,提问作者MustafaEsatTemel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 16:12:36