简体   繁体   English

如何将 ArrayList 的字符串写入文本文件?

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

I want to write an ArrayList<String> into a text file.我想将ArrayList<String>写入文本文件。

The ArrayList is created with the code: ArrayList是使用以下代码创建的:

ArrayList arr = new ArrayList();

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

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

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:创建 arrayList 和路径 object 代表您要写入的文件:

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:创建实际文件,并用 ArrayList 中的文本填充它:

Files.write(out,arrayList,Charset.defaultCharset());

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

If you need to create each ArrayList item in a single line then you can use this code如果您需要在一行中创建每个 ArrayList 项目,那么您可以使用此代码

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

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 implementsSerializable .如果您想将 ArrayList object 序列化为一个文件,以便您以后可以再次读回它,请使用 ObjectOuputStream/ObjectInputStream writeObject()/readObject(),因为ArrayList实现了。 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.如果是这样,那么安德烈的回答将做到这一点。

You might use ArrayList overloaded method toString()您可以使用 ArrayList 重载方法toString()

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

I think you can also use BufferedWriter:我认为您也可以使用 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;

Write a array list to text file using JAVA 使用 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM