62,620
社区成员
发帖
与我相关
我的任务
分享public class ComUserList {
private static File filePath = new File(System.getProperty("user.dir")
+ File.separator + "userNameList.db");
private static Collection<String> userList = null;
ComUserList(final String userName, Collection<String> myList)throws Exception{
if(filePath.exists()){
try{
myList = getArrayList();
myList.add(userName);
saveArrayList(myList);
}catch(EOFException e){
myList.add(userName);
saveArrayList(myList);
}catch(Exception e){
e.printStackTrace();
}
}else{
try{
filePath.createNewFile();
myList.add(userName);
saveArrayList(myList);
}catch(Exception e){
e.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
private static Collection<String> getArrayList()throws Exception{
ObjectInputStream readDB = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(filePath)));
userList = (Collection<String>)readDB.readObject();
readDB.close();
return userList;
}
private static void saveArrayList(Collection<String> list)throws Exception{
ObjectOutputStream writeDB = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(filePath)));
writeDB.writeObject(list);
writeDB.close();
}
}public class Test4 {
public static void main(String[] args)throws Exception{
//注释下面代码,可运行检测代码段
Collection<String> myList = new LinkedHashSet<String>();
String name = "111";
ComUserList cul = new ComUserList(name, myList);
Iterator<String> it = myList.iterator();
while(it.hasNext()){
System.out.println("yes2");
System.out.println(it.next());
}
//这是检测用的代码
// File filePath = new File(System.getProperty("user.dir")
// + File.separator + "userNameList.db");
// ObjectInputStream readDB = new ObjectInputStream(
// new BufferedInputStream(new FileInputStream(filePath)));
// Collection<String> userList = (Collection<String>)readDB.readObject();
// Iterator<String> it = userList.iterator();
// while(it.hasNext()){
// System.out.println(it.next());
// }
}
}