How to write an ArrayList of Strings into a text file?
Asked Answered
H

9

67

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());    
}
Hickey answered 1/7, 2011 at 12:48 Comment(5)
What's your desired output for this input?Manzanares
You code looks like it is reading a text file into an array. Is that what you actually mean?Frond
my code is reading a file and then tokenize it and store those tokens in an arraylist. now i want to write this arraylist into a file.Hickey
The answers all assume a different type of output. Can you give an example of how you want the output to look (or does it just need to be readable?)Frond
@kathy: I was trying to write this arraylist in a text file. Anyways, I have done that already with the help of Andrey's code. Thanks for replying.Hickey
P
118
import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt"); 
for(String str: arr) {
  writer.write(str + System.lineSeparator());
}
writer.close();
Politics answered 1/7, 2011 at 12:52 Comment(5)
define your array as: ArrayList<String> arr = new ArrayList<String>();Politics
what do you meann by arr?Syringomyelia
it's the name of the variable that holds reference to arrayPolitics
Where exactly would output.txt be situated in this case? Internal storage? - i.e. how to retrieve this file?Pisano
in current working directory (i.e. directory from which you started your java program)Politics
C
71

Java NIO

You can do that with a single line of code nowadays using Java NIO.

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 by calling on java.nio.file.Files utility class.

Files.write(out,arrayList,Charset.defaultCharset());
Consonant answered 29/7, 2014 at 18:12 Comment(3)
what is Files, what package is it from?Physicality
java.nio.file.Files, standard Java class since 1.7Englis
Nice and simple.Infeasible
D
22

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);
Dulcie answered 30/11, 2017 at 2:28 Comment(0)
D
5

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();
    }
Dropkick answered 10/3, 2016 at 23:3 Comment(2)
What if you open the same file and continue writing to it? I think have the last newline character is useful.Hipped
Yes it will be useful for append mode. Just comment the if condition and will work fine.Dropkick
N
4

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.

Nicolle answered 1/7, 2011 at 12:57 Comment(1)
I just want to add each item to a file but its showing an error message of incompatible type.Hickey
N
3

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));
Nonetheless answered 1/7, 2011 at 13:3 Comment(0)
L
1

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;
Levania answered 8/5, 2018 at 14:49 Comment(2)
This answer literally has nothing to do with ArrayLists of Strings, which is what the original poster was asking about.Longshore
@Kaiser Keister But all that's needed is to convert the ArrayLIst to a String which is easy to do in a loop with StringBuilder?Inch
L
-1

Write a array list to text file using JAVA

public void writeFile(List<String> listToWrite,String filePath) {

    try {
        FileWriter myWriter = new FileWriter(filePath);
        for (String string : listToWrite) {
            myWriter.write(string);
            myWriter.write("\r\n");
        }
        myWriter.close();
        System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}
Lactic answered 11/12, 2022 at 19:18 Comment(1)
Are you affiliated with the site? How is this better or worse than the other answers here?Bluma
S
-1
    FileWriter writer = new FileWriter("output.txt");
    Arrays.asStream(arr.stream()
            .forEach(i -> {
                try{
                        writer.write(i + ",");
                }
                catch (Exception e){}
                        
            }));
    writer.close();
Spectatress answered 24/12, 2023 at 11:24 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.