[英]Java doesn't display accent words correctly
我有一個java程序,它保存一個文本文件,然后在對話框中輸出它的內容。 當我在 IDE(BlueJ)中運行程序時,顯示如下:
正如您在對話框中看到的那樣,“1º)Mónica”行正確顯示。
但是,當我在IDE 外部運行相同的程序時,“Mónica”似乎不正確,如圖所示:
如何解決此問題始終顯示正確的輸出?
這是將文本文件讀取為字符串的代碼
public String recordesString()
{
Premios premios = new Premios();
File recordes = new File("recordes.txt");
if(!recordes.exists()) {
if(!client.isConnected())
openFTPSession();
downloadRecordes(); // this downloads the recordes.txt file
}
Scanner s = null;
try {
s = new Scanner(recordes);
} catch (Exception e) {
e.printStackTrace();
}
String string = "";
String linha = null;
for(int i = 1; s.hasNext(); i++) {
linha = s.nextLine();
String palavra[] = linha.split(" ",2);
string += i+"º) "+palavra[1] +" "+ premios.getPremio(Integer.parseInt(palavra[0]))+"\n";
}
s.close();
try {
Files.deleteIfExists(Paths.get(ficRecordes));
} catch (Exception e) {
e.printStackTrace();
}
return string;
}
掃描程序使用底層平台的默認字符集讀取文件。
請參閱http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
我希望該文件以UTF-8編碼,當您在IDE外部運行時,默認字符集是ISO-latin-1左右。 如果在創建掃描程序時指定文件的編碼,則結果將是可預測的。
s = new Scanner(recordes, "UTF-8");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.