Java outputting to text file?

后端 未结 5 699
悲哀的现实
悲哀的现实 2021-01-28 06:59

So I am having troubles printing to output. I understand the concept, but when it comes to this problem its kinda weird. I\'ve tried different print lines and all of them give m

5条回答
  •  余生分开走
    2021-01-28 07:52

    Cause of problem: In your code, everytime you call text(), you are replacing existing file, without updating or appending new data to it.

    Refer this SO question. You can write printWriter as

    PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
    

    I have tested on local, Try this code.

    public void text() {
        try {
            // Adding data to existing file without replacing it.
            PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("test.txt", true)));
            output.print(data[0]);
            for (int i = 1; i < data.length; i++) {
                output.printf(", %d", data[i]);
            }
            output.print("\n"); // Added next line in the file
            output.flush();
            output.close(); // closing PrintWriter.
        } catch (Exception ex) {
            // log your exception.
        }
    }
    

提交回复
热议问题