【发布时间】:2015-04-28 11:36:13
【问题描述】:
描述:
在我的程序中,要求用户输入一些值。这些值被存储到一个 ArrayList 中,以便我可以将它们打印出来。现在这个问题是一旦我终止程序,所有数据都会丢失。这就是为什么我决定将这些 arrayList 对象存储到文件中并从那里读取它们。
问题/问题:
我已经创建了所有相关的方法来写入和读取文件。但是文件中好像没有对象被读写。我主要关心的类是ReadWrite。
工作代码:
读写:
public void writeFile(List<PersonInfo> information) {
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
关于人:
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
rw.writeFile(info);
info2=rw.readFile();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
人物信息:
........
........
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
.........
.........
【问题讨论】:
-
你看到什么样的异常?
PersonalInfo可以序列化吗? -
流应该以相反的顺序关闭。如果 ObjectOutputStream 需要在 close() 上写一些东西,它不能因为底层文件已经关闭。顺便说一句,如果您使用 try-with-resources 它将以正确的顺序为您关闭资源。
-
你可以用
os.close();替换你的os.flush(); fos.close(); os.close();,或者使用try-with-resources更好。 -
AlexR,我还没有实现任何序列化和反序列化。我已经用过arrayList。
标签: java file-io arraylist fileinputstream fileoutputstream