[英]Java Scanner cannot read words with accent mark
I have problem with my CODE. 我的代码有问题。 IF I add words with accent mark to file, Scanner won´t read it.Thank you for help. 如果我在文件中添加带重音符号的单词,则Scanner不会读取它。谢谢您的帮助。
For example if file "names.txt" contains: John Lil None 例如,如果文件“ names.txt”包含:John Lil无
number of words in file is 3 文件中的单词数为3
but if contains: Jóhn Lil None 但如果包含:JóhnLil无
number of words in file is 0 文件中的单词数为0
CODE IS: 代码是:
File file=new File("names.txt");
Scanner skener=new Scanner(file);
int count=0;
while(skener.hasNext()){
aArrayListOfNames.add(skener.next());
count++;
}
skener.close();
System.out.println("Count is "+count);
return count;
Thank you all, problem FIXED! 谢谢大家,问题已解决! :D :D
Construct the Scanner by defining the charset it should use: 通过定义应使用的字符集来构造扫描器:
Scanner skener=new Scanner(file,"UTF-8");
I believe ASCII is the default charset for Scanner so that needs to be changed. 我相信ASCII是Scanner的默认字符集,因此需要进行更改。 Also the file might not be encoded in UTF-8. 此外,该文件可能未使用UTF-8编码。
I tried to get your error but it worked for me... 我试图得到您的错误,但对我有用。
private static void getStrings() throws FileNotFoundException {
List<String> nameArray = new ArrayList<String>();
File file = new File("C:\\Users\\XXX\\workspace\\stackoverflowtest1\\src\\stackoverflowtest1\\names.txt");
Scanner scanner= new Scanner(file);
int count = 0;
while (scanner.hasNext()) {
nameArray.add(scanner.next());
count++;
}
scanner.close();
System.out.println("Count is " + count);
System.out.println("1 - " + nameArray.get(0));
System.out.println("2 - " + nameArray.get(1));
System.out.println("3 - " + nameArray.get(2));
}
OUTPUT: 输出:
Count is 3
1 - Jóhn
2 - Lil
3 - None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.