爪哇 - 如何写的ArrayList对象为txt文件? [英] Java - How to write ArrayList Objects into txt file?
本文介绍了爪哇 - 如何写的ArrayList对象为txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
/ **我有一些喜欢的方法添加,显示,排序,删除,并退出该实施ArrayList的功能。它工作正常,但问题是,已经加入了该对象将不保存在一个.txt文件,只是临时对象。所以,我需要将它们添加到文本文件,这样我可以显示和后删除它们。这里的codeS的一部分。
* /
公共类的测试{ 公共静态无效的主要(字串[] args){
字符串命令;
INT索引= 0;
扫描仪输入=新的扫描仪(System.in);
ArrayList的<串GT; MenuArray =新的ArrayList<串GT;();
布尔OUT = FALSE;
而(!出来){
System.out.print(请输入您的命令:);
命令= input.nextLine();
//添加方法添加对象
如果(Command.startsWith(ADD)|| Command.startsWith(加)){
MenuArray.add(Command.substring(4).toLowerCase());
//索引对象
指数++;
/ **我坚持在这里,也不会写入input.txt中
但是BufferedWriter作家=新的BufferedWriter(新的FileWriter(
input.txt的));
尝试{
对于(字符串保存:MenuArray){
INT I = 0;
writer.write(++ I + + save.toString()。);
writer.write(\\ n);
}
} {最后
writer.close();
} * /
}否则如果(Command.startsWith(EXIT)|| Comand.startsWith(退出)){
出= TRUE;
}
}
}
}
解决方案
您可以使用的 的ObjectOutputStream
以对象写入一个文件:
{尝试
FOS的FileOutputStream =新的FileOutputStream(输出);
ObjectOutputStream的OOS =新的ObjectOutputStream(FOS);
oos.writeObject(MenuArray); //写MenuArray到的ObjectOutputStream
oos.close();
}赶上(例外前){
ex.printStackTrace();
}
/** I have some methods likes add,display,sort,delete,and exit that implemented the ArrayList function. It works correctly, but the problem is that the objects that had been added were not saved on a .txt file, just the temporary objects. So I need to add them into text file,so that I can display and delete them later. Here's the part of the codes. */
public class testing {
public static void main(String[] args) {
String Command;
int index = 0;
Scanner input = new Scanner(System.in);
ArrayList<String> MenuArray = new ArrayList<String>();
boolean out = false;
while (!out) {
System.out.print("Enter your Command: ");
Command = input.nextLine();
// method ADD for adding object
if (Command.startsWith("ADD ") || Command.startsWith("add ")) {
MenuArray.add(Command.substring(4).toLowerCase());
// indexing the object
index++;
/** i stuck here,it won't written into input.txt
BufferedWriter writer = new BufferedWriter(new FileWriter(
"input.txt"));
try {
for (String save : MenuArray) {
int i = 0;
writer.write(++i + ". " + save.toString());
writer.write("\n");
}
} finally {
writer.close();
}*/
} else if (Command.startsWith("EXIT") || Comand.startsWith("exit")) {
out = true;
}
}
}
}
解决方案
You can use ObjectOutputStream
to write an object into a file:
try {
FileOutputStream fos = new FileOutputStream("output");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(MenuArray); // write MenuArray to ObjectOutputStream
oos.close();
} catch(Exception ex) {
ex.printStackTrace();
}
这篇关于爪哇 - 如何写的ArrayList对象为txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文