2014-02-12 45 views
2

我在寫一個翻譯程序,它從文本文件中讀取翻譯。此方法從文本文件讀取並將其添加到我用於字典的Map對象。Java readLine()無法正常工作

public Map<String, String> loadTranslations() throws IOException { 
    Map<String, String> translations = new HashMap<String, String>(); 
    BufferedReader in = null; 
    try { 
     in = new BufferedReader(new FileReader(System.getProperty("user.dir") + "\\resource\\translations.txt")); 
     englWord = in.readLine(); 
     frenWord = in.readLine(); 
     translations.put(englWord, frenWord); 
     System.out.println(englWord + "\n" + frenWord + "\n" + translations); 
    } catch(Exception e) { 
     JOptionPane.showMessageDialog(this, "An Error Occured!", "Error!", JOptionPane.ERROR_MESSAGE); 
     e.printStackTrace(); 
    } finally { 
     in.close(); 
    } 
    JOptionPane.showMessageDialog(this, "Updated!", "", JOptionPane.INFORMATION_MESSAGE); 
    return translations; 
} 

但每當我運行它,而不是打印從它打印這個文本文件中的話。

潮攍ੵ漬ੴ睯ഊ摥畸ഊ瑨牥攍ੴ牯楳ഊ景畲ഊ煵慴牥ഊ晩癥ഊ捩湱ഊ獩砍ੳ楸ഊ獥癥漬ੳ數琍੥楧桴ഊ桵楴ഊ湩湥ഊ湥畦ഊ瑥漬੤楸 
null 
{潮攍ੵ漬ੴ睯ഊ摥畸ഊ瑨牥攍ੴ牯楳ഊ景畲ഊ煵慴牥ഊ晩癥ഊ捩湱ഊ獩砍ੳ楸ഊ獥癥漬ੳ數琍੥楧桴ഊ桵楴ഊ湩湥ഊ湥畦ഊ瑥漬੤楸=null} 

該文本文件只列出了英語和法語的前10個字母,所以輸出應該是類似的;

one 
un 
{one=un} 

我該如何解決這個問題?

+1

這絕對是Java的錯。 –

回答

3

如果您未指定編碼,您將獲得一個默認值depends on how the JVM gets initialized。你可以指定一個明確的編碼,如下所示:

FileInputStream fis = new FileInputStream("test.txt"); 
    InputStreamReader isr = new InputStreamReader(fis, "UTF8"); 
    BufferedReader in = new BufferedReader(isr); 

這段代碼讀取一個文件,它假定內容以UTF8編碼。

請參閱Oracle tutorial on Character and Byte Streams