通过ObjectInputStream的writeObject方法写入List<String>这个时候不会报错,
取数据通过readObject方法报了一个错WriteAbortedException
请问下有什么办法可以解决这个问题,或者还有其他实现方式。
------解决方案--------------------
报错?
实在不行就自己写个类,实现serializable接口。把list放入。
------解决方案--------------------
String 貌似要实现serializable接口,有点麻烦啊。这个以前真没注意过。
------解决方案--------------------
- Java code
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(); } } } }
------解决方案--------------------
这个不太熟悉,是这个意思吗?我这个貌似没啥错。。。
- Java code
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); }}