javafileiofileoutputstreamcorrupt-data

Java - Get Japanese from JTextField and save to File


I am trying to get Japanese input from a JTextField (with the getText() method) and saving that to a File. I am confident that it does get Japanese format from the JTextField since I can append() that String to a JTextArea and it will be in the correct Japanese Format.

However, when I try to write to a File it only turns to gibberish! I have tried to use an OutputStreamWriter instantiated with StandardCharsets.UTF_8 and I have tried with a plain FileOutputStream where I send in the bytes from calling getBytes(StandardCharsets.UTF_8) on the String. In both cases the resulting file looks more like the following:

日本語�難������学����ら�日本��む

Which is not what I want, naturally. Does anyone have any idea what the issue might be?


Solution

  • I'm pretty sure you are creating the file with ISO-8859-1 instead UTF-8. I'm also inferring you are using Eclipse because your previous questions.

    Change your workspace settings

    Window -> Preferences -> General -> Workspace : UTF-8

    enter image description here

    Default encoding for all content types

    enter image description here

    TestClass

    This is the class i used to test the theory

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    
    public class test {
        public static void main(String[] args) throws IOException {
                File fileDir = new File("test.txt");
                String japanese = "路権ち点節ヤトツ限聞ド勇売質タカア";
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir)));
                out.append(japanese);
                System.out.println(japanese);
                out.flush();
                out.close();
        }
    }
    

    Input/output with different settings

    OutputFileISO: 路権ã¡ç¹ç¯ã¤ããéèãå売質ã¿ã«ã¢

    OutputFileUTF8: 路権ち点節ヤトツ限聞ド勇売質タカア