无法使用 java 从控制台将德语“变音符号”(??ü)写入文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3862320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Failing to write german 'umlauts' (??ü) from console to text file with java
提问by yan.kun
currently I'm desperately trying to write german umlauts, read from the console, into a utf8 encoded text file on windows 7.
目前,我正拼命地尝试将从控制台读取的德语变音符号写入 Windows 7 上的 utf8 编码文本文件。
Here is the code to setup the scanner:
这是设置扫描仪的代码:
Scanner scanner = new Scanner(System.in, "UTF8");
Here is the code to read the string:
这是读取字符串的代码:
String s = scanner.nextLine();
Here is the code to write into a file:
这是写入文件的代码:
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(this.targetFile), "UTF8");
osw.write(s);
Unfortunately, instead of example "überraschung" the so written file is encoded in utf8 but will not display the umlaut. What to do?
不幸的是,这样写的文件不是示例“überraschung”,而是以 utf8 编码,但不会显示变音。该怎么办?
回答by Grodriguez
Your console probably is not UTF-8, so when you do new Scanner(System.in, "UTF8");
you are creating a scanner with the wrong encoding, and your umlauts are lost when you try to read lines from the console.
您的控制台可能不是 UTF-8,因此当您new Scanner(System.in, "UTF8");
使用错误的编码创建扫描仪时,当您尝试从控制台读取行时,您的变音符号会丢失。
You may want to use chcp
on a console prompt to check what code page is being used.
您可能希望chcp
在控制台提示上使用来检查正在使用的代码页。
In fact, you might not need to specify an encoding at all. If you just create the scanner as new Scanner(System.in)
, the default platform encoding should be used.
事实上,您可能根本不需要指定编码。如果您只是将扫描仪创建为new Scanner(System.in)
,则应使用默认平台编码。
回答by MyName
I had a similar problem (The String "?" would not be "detected" by the Scanner and Strings like "A?ores" would have the ? character "garbled").
我有一个类似的问题(字符串“?”不会被扫描仪“检测到”,像“A?ores”这样的字符串会有 ? 字符“乱码”)。
I solved it by declaring the charset for the language:
我通过声明语言的字符集解决了这个问题:
Scanner keyboardReader = new Scanner(System.in, "iso-8859-1");
回答by greuze
This worked for me, with german umlauts:
这对我有用,有德国变音:
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class P {
public static void main(String[] args) throws Exception {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s = stdin.readLine();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:/p.txt"), "UTF-8");
osw.write(s);
osw.close();
}
}