Java ArrayList保存到文本文件

Java ArrayList保存到文本文件,java,arraylist,text-files,Java,Arraylist,Text Files,我想将arraylist的内容保存到文本文件中。到目前为止,我所做的如下所示,而不是添加x.format(“%s%s”、“100”、“control1”);在文本文件中,我想从arraylist添加对象,我该怎么做 import java.util.*; public class createfile { ArrayList<String> control = new ArrayList<String>(); private Formatter x;

我想将arraylist的内容保存到文本文件中。到目前为止,我所做的如下所示,而不是添加x.format(“%s%s”、“100”、“control1”);在文本文件中,我想从arraylist添加对象,我该怎么做

import java.util.*;

public class createfile
{
    ArrayList<String> control = new ArrayList<String>();

    private Formatter x;

    public void openFile()
    {
        try {
            x = new Formatter("ControlLog.txt");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error: Your file has not been created");
        }
    }

    public void addRecords()
    {
        x.format("%s%s", "100", "control1");
    }

    public void closeFile()
    {
        x.close();
    }
}

public class complete
{
    public static void main(String[] args)
    {
        createfile g = new createfile();
        g.openFile();
        g.addRecords();
        g.closeFile();
    }
}
import java.util.*;
公共类创建文件
{
ArrayList控件=新建ArrayList();
专用格式化程序x;
公共void openFile()
{
试一试{
x=新格式化程序(“ControlLog.txt”);
}捕获(例外e){
showMessageDialog(null,“错误:您的文件尚未创建”);
}
}
公共档案(
{
x、 格式(“%s%s”、“100”、“control1”);
}
公共文件()
{
x、 close();
}
}
公共类完成
{
公共静态void main(字符串[]args)
{
createfile g=新建createfile();
g、 openFile();
g、 addRecords();
g、 closeFile();
}
}

ArrayList和String都可以实现。由于您有一个字符串的ArrayList,因此可以将其写入文件,如下所示:

 FileOutputStream fos = new FileOutputStream("path/to/file");
 ObjectOutputStream out = new ObjectOutputStream(fos);
 out.writeObject(myArrayList);  //Where my array list is the one you created
 out.close();
这是一个非常好的教程,向您展示了如何将java对象写入文件

写入的对象可以以类似的方式从文件中读回

FileInputStream in = new FileInputStream("path/to/file");
ObjectInputStream is = new ObjectInputStream(in);
myArrayList = (ArrayList<String>) is.readObject(); //Note that you will get an unchecked warning here
is.close()
FileInputStream in=newfileinputstream(“path/to/file”);
ObjectInputStream is=新的ObjectInputStream(in);
myArrayList=(ArrayList)是.readObject()//请注意,您将在此处收到未选中的警告
is.close()

是一个关于如何从文件中读回对象的教程。

我认为您需要首先创建一个ArrayList。然后迭代ArrayList元素(可能使用for块),对每个元素进行格式化,并将格式化后的字符串打印到filewriter中。我可以问一下它的用途吗?是的,我已经创建了一个ArrayList,如上所示。这些元素取决于用户输入,因此很明显,我现在无法添加这些元素。我只是想知道如何为我正在尝试的项目将arrayList写入textfileIts,以便更好地理解java。我是个新手!