我想将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();
}
}
答案 0 :(得分:0)
ArrayList和String都实现了Serializable。由于您有一个StringList的字符串,您可以将其写入文件,如下所示:
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();
Here 是一个非常好的教程,向您展示如何将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()
Here是一个关于如何从文件中读取对象的教程。