将.txt文件读取到地图然后再次将其另存为.txt?

时间:2017-08-28 16:17:35

标签: java text save

我在阅读和保存.txt文件

时遇到了一些麻烦

.txt文件是带有单词的Wordlist,其中每个单词也都有一个附加数字(整数)。所以它看起来像:

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
}

1 个答案:

答案 0 :(得分:0)

尝试按以下方式阅读文件:

BufferedReader in = new BufferedReader(
       new InputStreamReader(
                  new FileInputStream(file), "UTF8"));
相关问题