68

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());    
}
5
  • What's your desired output for this input? Commented Jul 1, 2011 at 13:00
  • You code looks like it is reading a text file into an array. Is that what you actually mean? Commented Jul 1, 2011 at 13:02
  • 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. Commented Jul 1, 2011 at 13:11
  • 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?) Commented Jul 1, 2011 at 15:03
  • @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. Commented Jul 5, 2011 at 11:35

9 Answers 9

118
import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt"); 
for(String str: arr) {
  writer.write(str + System.lineSeparator());
}
writer.close();
Sign up to request clarification or add additional context in comments.

5 Comments

define your array as: ArrayList<String> arr = new ArrayList<String>();
what do you meann by arr?
it's the name of the variable that holds reference to array
Where exactly would output.txt be situated in this case? Internal storage? - i.e. how to retrieve this file?
in current working directory (i.e. directory from which you started your java program)
73

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

3 Comments

what is Files, what package is it from?
java.nio.file.Files, standard Java class since 1.7
Nice and simple.
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);

Comments

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

2 Comments

What if you open the same file and continue writing to it? I think have the last newline character is useful.
Yes it will be useful for append mode. Just comment the if condition and will work fine.
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.

1 Comment

I just want to add each item to a file but its showing an error message of incompatible type.
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));

Comments

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;

2 Comments

This answer literally has nothing to do with ArrayLists of Strings, which is what the original poster was asking about.
@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?
-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();
    }
}

1 Comment

Are you affiliated with the site? How is this better or worse than the other answers here?
-1
    FileWriter writer = new FileWriter("output.txt");
    Arrays.asStream(arr.stream()
            .forEach(i -> {
                try{
                        writer.write(i + ",");
                }
                catch (Exception e){}
                        
            }));
    writer.close();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.