我有一些麻煩讀取並保存.txt
文件將.txt文件讀入地圖,然後再次保存爲.txt文件?
的.txt
文件是用語言,每一個字也有一個附加號碼(整數)一個單詞表。因此,它看起來像:
hello,0
bye,3
maby,0
...
我已經創建了閱讀和與他們的數字字加載到該問題的功能,這是不工作的,我需要,因爲我從德國很特殊字符。
每個特殊字符都被傳送到一個?
或一個空白塊。所以我需要一些幫助來修改我的讀取和保存功能,以便能夠保存並讀取ä
,ö
, ü
和ß
字符。
public void loadWordList(Map<String,Integer> map){
try{
File toRead=new File("Wortliste.txt");
FileInputStream fis=new FileInputStream(toRead); // Ist bereits in einer Try and Catch
Scanner sc=new Scanner(fis);
Map<String,String> mapInFile=new HashMap<String,String>();
//read data from file line by line:
String currentLine;
while(sc.hasNextLine()){
currentLine=sc.nextLine();
//now tokenize the currentLine:
StringTokenizer st=new StringTokenizer(currentLine,",",false);
//put tokens ot currentLine in map
map.put(st.nextToken(),Integer.parseInt(st.nextToken()));
}
fis.close();
}catch(Exception e){System.out.println("Wortliste konnte nicht gefunden werden");} // Ist bereits in einer Try and Catch
}
//******************************************************************************
//Speichern der Wordliste für Wortvorschläge
//******************************************************************************
public void saveWordList(Map<String,Integer> map){
try{
File fileTwo=new File("Wortliste.txt");
FileOutputStream fos=new FileOutputStream(fileTwo); // Ist bereits in einer Try and Catch
PrintWriter pw=new PrintWriter(fos);
for(Map.Entry<String,Integer> m :map.entrySet()){ // Andere schreibweise
pw.println(m.getKey()+","+m.getValue());
}
System.out.println("Word gespeichert");
pw.flush();
pw.close();
fos.close();
}catch(Exception e){System.out.println("Wortliste konnte nicht gespeichert werden");} // Ist bereits in einer Try and Catch
}
我一直以爲Java中使用Unicode字符串 - 這應該與這些字符自動處理... –
這可能幫助:https://stackoverflow.com/questions/9852978/write-a-file-in-utf-8-using-filewriter-java –