在我的程序中,用户输入一些string
和int
值,并将它们存储在具有动态大小的ArrayList中。
现在我想将这些对象存储在磁盘上,以便在关闭应用程序后不会丢失任何数据。最后我想读取文件。我正在上课的是:ReaderWriter
我的代码:
主:
public class PeopleInfo {
public static void main(String[] args) {
System.out.println("WELCOME TO MY PERSONAL DATABASE\n\n");
Scanner input = new Scanner(System.in);
List<PeopleObject> peopleObject = new ArrayList<PeopleObject>();
String name;
int age;
int option;
while (true) {
System.out.println("1. Enter info\n"
+ "2. Print them out\n"
+ "3. Exit\n"
+ "*********"
+ "*********\n");
option = input.nextInt();
input.nextLine();
switch (option) {
case 1:
PeopleObject p_object = new PeopleObject();
System.out.println("Enter your friends name:");
p_object.setName(input.nextLine());
System.out.println("Enter age: ");
p_object.setAge(input.nextInt());
peopleObject.add(p_object);
System.out.println("\n");
break;
case 2:
System.out.println("Name \tage");
for (PeopleObject printPeopleObject : peopleObject) {
System.out.println(printPeopleObject);
}
System.out.println("\n\n");
break;
case 3:
return;
}
}
}
}
PeopleObject:
public class PeopleObject {
private String name;
private int age;
public PeopleObject() {
this.name = null;
this.age = 0;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return name + "\t\t" + age;
}
}
读写器:
public class ReaderWriter {
//I want to use this class for storing my info in a file
//and retrieving them
public void writeToFile(){
try{
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
public String readFromFile(){
//return info;
}
}