I want to write an ArrayList
into a text file.
The ArrayList
is created with the code:
ArrayList arr = new A
I think you can also use BufferedWriter :
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("note.txt")));
String stuffToWrite = info;
writer.write(stuffToWrite);
writer.close();
and before that remember too add
import java.io.BufferedWriter;
If you need to create each ArrayList item in a single line then you can use this code
private void createFile(String file, ArrayList<String> arrData)
throws IOException {
FileWriter writer = new FileWriter(file + ".txt");
int size = arrData.size();
for (int i=0;i<size;i++) {
String str = arrData.get(i).toString();
writer.write(str);
if(i < size-1)**//This prevent creating a blank like at the end of the file**
writer.write("\n");
}
writer.close();
}
import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt");
for(String str: arr) {
writer.write(str + System.lineSeparator());
}
writer.close();
You can do that with a single line of code nowadays. Create the arrayList and the Path object representing the file where you want to write into:
Path out = Paths.get("output.txt");
List<String> arrayList = new ArrayList<> ( Arrays.asList ( "a" , "b" , "c" ) );
Create the actual file, and fill it with the text in the ArrayList:
Files.write(out,arrayList,Charset.defaultCharset());
I would suggest using FileUtils from Apache Commons IO library.It will create the parent folders of the output file,if they don't exist.while Files.write(out,arrayList,Charset.defaultCharset());
will not do this,throwing exception if the parent directories don't exist.
FileUtils.writeLines(new File("output.txt"), encoding, list);
If you want to serialize the ArrayList object to a file so you can read it back in again later use ObjectOuputStream/ObjectInputStream writeObject()/readObject() since ArrayList implements Serializable. It's not clear to me from your question if you want to do this or just write each individual item. If so then Andrey's answer will do that.