简体   繁体   中英

In Java when writing an array to file, only the last line is written

I am trying to write an array to a file using a loop, but every time I open the text file it only shows the last line. If I write the array directly with a toString it has the extra spaces and array characters I don't want. Here is my code for writing to the array

WriteFile data = new WriteFile(file_namec2g , true);
for (String s : full) {try {
data.writeToFile(s );
} catch (IOException ex) {
Logger.getLogger(CC2LevelManagerUI.class.getName()).log(Level.SEVERE, null, ex);
}
}

Write file is my file writing class. I can post that in another comment if it would be useful. It is one I found on the internet.File_namec2g is the name of the file and the true is if it overwrites or not. So my question is how can I get the array to print line by line into a text file that will show up as such in a program like notepad?

Based on your comment, you are creating a new PrintWriter object each time you call data.writeToFile() . Instead, create the object in the WriteFile constructor and then create a method in WriteFile called save() (or similar) that calls the close() method on the PrintWriter object. Call that method once you have written all of the text in your loop.

WriteFile data = new WriteFile(file_namec2g , true);
for (String s : full) {
try {
    data.writeToFile(s );
} catch (IOException ex) {
    Logger.getLogger(CC2LevelManagerUI.class.getName()).log(Level.SEVERE, null, ex);
}
data.save() // Save the changes to the file

In WriteFile

public void save(){
    pw.close(); // Replace "pw" with the name of the `PrintWriter` object
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM