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

后端 未结 7 1072
不思量自难忘°
不思量自难忘° 2020-11-27 15:47

I want to write an ArrayList into a text file.

The ArrayList is created with the code:

ArrayList arr = new A         


        
相关标签:
7条回答
  • 2020-11-27 16:07

    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;
    
    0 讨论(0)
  • 2020-11-27 16:11

    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();
        }
    
    0 讨论(0)
  • 2020-11-27 16:19
    import java.io.FileWriter;
    ...
    FileWriter writer = new FileWriter("output.txt"); 
    for(String str: arr) {
      writer.write(str + System.lineSeparator());
    }
    writer.close();
    
    0 讨论(0)
  • 2020-11-27 16:19

    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());
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-27 16:20

    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.

    0 讨论(0)
提交回复
热议问题