簡體   English   中英

如何將 ArrayList 的字符串寫入文本文件?

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

我想將ArrayList<String>寫入文本文件。

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

你現在可以用一行代碼來做到這一點。 創建 arrayList 和路徑 object 代表您要寫入的文件:

Path out = Paths.get("output.txt");
List<String> arrayList = new ArrayList<> ( Arrays.asList ( "a" , "b" , "c" ) );

創建實際文件,並用 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()); 不會這樣做,如果父目錄不存在則拋出異常。

FileUtils.writeLines(new File("output.txt"), encoding, list);

如果您需要在一行中創建每個 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();
    }

如果您想將 ArrayList object 序列化為一個文件,以便您以后可以再次讀回它,請使用 ObjectOuputStream/ObjectInputStream writeObject()/readObject(),因為ArrayList實現了。 從你的問題中我不清楚你是想這樣做還是只寫每個單獨的項目。 如果是這樣,那么安德烈的回答將做到這一點。

您可以使用 ArrayList 重載方法toString()

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

我認為您也可以使用 BufferedWriter:

BufferedWriter writer = new BufferedWriter(new FileWriter(new File("note.txt")));

String stuffToWrite = info;

writer.write(stuffToWrite);

writer.close();

在此之前記得添加

import java.io.BufferedWriter;

使用 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