日期:2014-05-20 浏览次数:20882 次
public class TestObjectWR { public static void main(String[] args) { File f = new File("serialize"); if(!f.exists()) try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream(f)); List<String> strs = new ArrayList<String>(); strs.add("foo"); strs.add("bar"); out.writeObject(strs); out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(out!=null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } ObjectInputStream in = null; try { in = new ObjectInputStream(new FileInputStream(f)); List<String> list = (List<String>) in.readObject(); for(String s:list) System.out.println(s); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally{ if(in!=null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
------解决方案--------------------
这个不太熟悉,是这个意思吗?我这个貌似没啥错。。。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; public class StringTest { public static void main(String[] args) throws Exception { List<String> sList = new ArrayList<String>(); sList.add("123"); sList.add("123"); sList.add("123"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("slist.txt")); oos.writeObject(sList); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("slist.txt")); List<String> sList2 = (ArrayList<String>)ois.readObject(); ois.close(); System.out.println(sList2); } }