我试图用FileOutputStream创建一个文件,但它总是创建ANSI格式,如下图所示。我在上设置了所有字符代码,但问题仍然相同。
这是我的密码:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class sss {
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
发布于 2022-09-29 14:13:43
不要在那里使用ObjectOutputStream
;即二进制java对象。避免序列化;它实际上是不推荐的。此外,Serializable还存储类数据。
try (FileOutputStream fout=new FileOutputStream("f.txt")) {
fout.write(s1.name.getBytes(StandardCharsets.UTF_8));
} // Closes fout.
“错误”可能导致最新的字符串类(通常作为UTF-16字符的数组保存Unicode )也可以容纳ANSI字节数组。
另外,硬编码一个字符串(new Student(211,"ravi");
),这意味着保存java源代码的编辑器和javac编译器必须使用相同的编码来生成.class文件。否则,字符串将被破坏。
try {
//Creating the object
Student s1 = new Student(212, "Jérome");
//Creating stream and writing the object
Path path = Paths.get("f.txt");
Files.writeString(path, s1.name); // Default UTF-8
path = path.resolveSibling("f-latin1.txt");
Files.writeString(path, s1.name, StandardCharsets.ISO_8859_1);
System.out.println("success");
} catch (Exception e) {
e.printStackTrace(System.out);
}
https://stackoverflow.com/questions/73896770
复制相似问题