Reputation: 4470
I have a list of lists to write in a text file :
ArrayList<ArrayList<String>> list = new ArrayList<>();
Sample List:
[["sample_string_one","sample_string_two","sample_string_three"],["sample_string_four","sample_string_five","sample_string_six"]]
Writing to text file:
Path sPath = Paths.get("output.txt");
for (ArrayList sampleArr: list){
Files.write(sPath,sampleArr);
}
Error:
The code works, but the error is the contents of the file output.txt
gets updated.
Expected Contents of output.txt
:
sample_string_one
sample_string_two
sample_string_three
sample_string_four
sample_string_five
sample_string_six
Original Contents:
sample_string_four
sample_string_five
sample_string_six
Essentially, the content of the file gets updated with the latest inner list in the list of lists. Any suggestions to solve this would be great.
Upvotes: 0
Views: 935
Reputation: 2166
Try this:
Files.write(path, list, StandardOpenOption.APPEND);
From the documentation: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-byte:A-java.nio.file.OpenOption...-
If no options are present then this method works as if the
CREATE
,TRUNCATE_EXISTING
, andWRITE
options are present.
public static final StandardOpenOption TRUNCATE_EXISTING
If the file already exists and it is opened forWRITE
access, then its length is truncated to 0. This option is ignored if the file is opened only forREAD
access.
What you want is:
public static final StandardOpenOption APPEND
If the file is opened forWRITE
access then bytes will be written to the end of the file rather than the beginning. If the file is opened for write access by other programs, then it is file system specific if writing to the end of the file is atomic.
Upvotes: 2