Ricky
Ricky

Reputation: 2374

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

Upvotes: 68

Views: 287772

Answers (9)

Roberto
Roberto

Reputation: 1395

    FileWriter writer = new FileWriter("output.txt");
    Arrays.asStream(arr.stream()
            .forEach(i -> {
                try{
                        writer.write(i + ",");
                }
                catch (Exception e){}
                        
            }));
    writer.close();

Upvotes: -1

gabinetex
gabinetex

Reputation: 721

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

Upvotes: 72

Sanjay singh
Sanjay singh

Reputation: 9

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

Upvotes: -1

Andrey Adamovich
Andrey Adamovich

Reputation: 20683

import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt"); 
for(String str: arr) {
  writer.write(str + System.lineSeparator());
}
writer.close();

Upvotes: 118

Sahar
Sahar

Reputation: 49

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;

Upvotes: 1

chao_chang
chao_chang

Reputation: 778

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

Upvotes: 22

Joseph Selvaraj
Joseph Selvaraj

Reputation: 2237

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

Upvotes: 5

stemm
stemm

Reputation: 6050

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

Upvotes: 3

ribram
ribram

Reputation: 2460

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.

Upvotes: 4

Related Questions