本来要做一个地铁线路信息的保存,所以有多条线路,就想着用arraylist型数组进行保存,在写入时每次都只是写入一个ArrayList型,读出时是打算以arraylist数组把所有读出,但现在问题就是读完第一个后就无法继续读取了,求大家帮助
源码如下
package subway;
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class Subwayarraylist {
private ArrayList<Subwayinformation> notes = new ArrayList<Subwayinformation>();
int site;
Scanner scan;
ArrayList<Subwayinformation> list[]=new ArrayList[20];
Subwayinformation a;
public void created()
{
Scanner scan=new Scanner(System.in);
System.out.println("请输入线路");
site=scan.nextInt();
int i=1;
while(i==1)
{
Subwayinformation a=new Subwayinformation();
a.setinformation();
notes.add(a);
System.out.println("继续输入按1,退出按0");
i=scan.nextInt();
}
savearraylist();
}
public void savearraylist()
{
try {
FileOutputStream fileout=new FileOutputStream("arraylist.txt",true);
ObjectOutputStream objectOut=new ObjectOutputStream(fileout);
objectOut.writeObject(notes);
objectOut.close();
System.out.println("文件已成功写入");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readlist() throws IOException, ClassNotFoundException
{
int i1=0;
File file=new File("arraylist.txt");
FileInputStream filein = new FileInputStream(file);
ObjectInputStream objectin = new ObjectInputStream(filein);
try {
while (true) {
list[i1]=((ArrayList<Subwayinformation>) objectin.readObject());
i1+=1;
}
}
catch(EOFException e){
System.out.println("读取完成");
}
ArrayList a;
Subwayinformation d;
a=list[0];
d=(Subwayinformation)a.get(2);
System.out.println(d.site);
System.out.println(d.line);
}
}
用对象,然后序列化反序列化。直接把对象存储到文件内,那是个啥呀
哎,懒得看下去
created 函数执行了几次?
我感觉你只执行了一次,因为,每次调用 created 函数,都会向 arraylist.txt 文件中写入数据。(注意,重复写入会覆盖掉原有的数据。)
如果 created 函数只执行了一次,那么,就会只写入一次 arraylist.txt 文件,这个文件中存放的是一个 ArrayList 对象,
那么,你的 readlist 函数里面,没有必要循环读取,因为 readlist.txt 文件中只存放了一个 ArrayList 对象。
如果 created 函数执行了多次,就会多次调用 savearraylist 函数,从而造成 arraylist.txt 文件的重复写入问题,后写入的数据会覆盖前一次写入的数据,文件中永远只保存了一个 ArrayList 对象。
那么, readlist 函数里面的循环读取,依然没有什么意义吧,文件中,只有一个 ArrayList 对象。
这里可能有问题
int i = 1;
while (i == 1) {
Subwayinformation a = new Subwayinformation();
a.setinformation();
notes.add(a);
System.out.println("继续输入按1,退出按0");
i = scan.nextInt();
}
改成
do {
System.out.println("请输入信息,退出请按0");
int i = scan.nextInt();
if (i == 0) {
break;
}
Subwayinformation a = new Subwayinformation();
a.setinformation();
} while (true);