[java] How to write an ArrayList of Strings into a text file?

I want to write an ArrayList<String> into a text file.

The ArrayList is created with the code:

ArrayList arr = new ArrayList();

StringTokenizer st = new StringTokenizer(
    line, ":Mode set - Out of Service In Service");

while(st.hasMoreTokens()){
    arr.add(st.nextToken());    
}

This question is related to java

The answer is


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());

You might use ArrayList overloaded method toString()

String tmp=arr.toString();
PrintWriter pw=new PrintWriter(new FileOutputStream(file));
pw.println(tmp.substring(1,tmp.length()-1));

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();
    }

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 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.


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);