用对象流读取,大多数向量、集合都实现了序列化,所以实现起来很简单
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.TreeSet;
import java.util.Vector;
public class outStream {
static TreeSetv = new TreeSet ();
// static Vectorv = new Vector ();
static File fdata = new File("hello/data");
public static void main(String[] args) {
boolean flag = false; //读、存标志
if(flag){
for(int i = 9; i > 0; i--){
v.add("name" + i);
}
saveVector(); // 存储数据
System.out.println("已经存储完毕,修改flag值可读取数据");
}
if (!flag){
readVector(); //读取操作
}
}
private static void saveVector() {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fdata));
oos.writeObject(v);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readVector() {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fdata));
// v = (Vector) ois.readObject();
v = (TreeSet) ois.readObject();
ois.close();
for (String e : v) {
System.out.println(e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
你刚开始的flag应该是true吧