小编典典

用Java写入TextFile

java

嗨,我正在尝试将字符串写入文本文件,但是有一个小问题。我在该站点上其他问题的帮助下完成了代码,但是当我尝试向文本文件中添加字符串时,它将擦除该文本文件中的所有内容并写入输入。但我希望它转到下一行并编写。我无法解决。我将不胜感激任何帮助。谢谢..

public static void addCar() throws IOException{

        String string = transferBrand;
        String string2 = ":"+transferModel;
        System.out.println(string+string2);
        File file = new File("HatchBack.txt");
        try {
            StringReader stringReader = new StringReader(string+string2);
            BufferedReader bufferedReader = new BufferedReader(stringReader);
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            for(String line = bufferedReader.readLine(); line != null; line =bufferedReader.readLine()) {               
                bufferedWriter.write(line);
                bufferedWriter.newLine();                   
            }
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }       
}

阅读 308

收藏
2020-11-30

共1个答案

小编典典

(未试用)您是否尝试过JavaDoc中提到的方法?

FileWriter fileWriter = new FileWriter(file, true);
2020-11-30