Java - Get Japanese from JTextField and save to File

会有一股神秘感。 提交于 2020-01-06 07:10:34

问题


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?


回答1:


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

Default encoding for all content types

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: 路権ち点節ヤトツ限聞ド勇売質タカア



来源:https://stackoverflow.com/questions/53810121/java-get-japanese-from-jtextfield-and-save-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!