javautf-8encodeansi

Java exports ANSI file instead of UTF-8


I'm trying to create a file with FileOutputStream, but it always creates ANSI format like the picture below. I made all character encode settings on Eclipse and IntelliJ, but still same issue.

Character problems on ANSI

And here is my code:

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);}    
         }    
    
}

Solution

  • Do not use ObjectOutputStream there; that is for binary java objects. Avoid Serializable; it is practicably deprecated. Also Serializable also stores the class data.

    try (FileOutputStream fout=new FileOutputStream("f.txt")) {
        fout.write(s1.name.getBytes(StandardCharsets.UTF_8));
    } // Closes fout.
    

    The "error" might be caused that the latest String class, which will hold Unicode, normally as array of UTF-16 chars, can also hold an ANSI byte array.

    Also you hard-code a string (new Student(211,"ravi");) which means that the editor saving the java source and the javac compiler must use the same encoding to generate a .class file. When not the string will be corrupted.

      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);
      }