Java語言只能將實現了Serializable接口的類的對象保存到文件中,利用如下方法即可:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public static void writeObjectToFile(Object obj) { File file = new File( "test.dat" ); FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut= new ObjectOutputStream(out); objOut.writeObject(obj); objOut.flush(); objOut.close(); System.out.println( "write object success!" ); } catch (IOException e) { System.out.println( "write object failed" ); e.printStackTrace(); } } |
參數obj一定要實現Serializable接口,否則會拋出java.io.NotSerializableException異常。另外,如果寫入的對象是一個容器,例如List、Map,也要保證容器中的每個元素也都是實現 了Serializable接口。例如,如果按照如下方法聲明一個Hashmap,并調用writeObjectToFile方法就會拋出異常。但是如果是Hashmap<String,String>就不會出問題,因為String類已經實現了Serializable接口。另外如果是自己創建的類,如果繼承的基類沒有實現Serializable,那么該類需要實現Serializable,否則也無法通過這種方法寫入到文件中。
1
2
3
4
5
|
Object obj= new Object(); //failed,the object in map does not implement Serializable interface HashMap<String, Object> objMap= new HashMap<String,Object>(); objMap.put( "test" , obj); writeObjectToFile(objMap); |
2.從文件中讀取對象
可以利用如下方法從文件中讀取對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public static Object readObjectFromFile() { Object temp= null ; File file = new File( "test.dat" ); FileInputStream in; try { in = new FileInputStream(file); ObjectInputStream objIn= new ObjectInputStream(in); temp=objIn.readObject(); objIn.close(); System.out.println( "read object success!" ); } catch (IOException e) { System.out.println( "read object failed" ); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return temp; } |
讀取到對象后,再根據對象的實際類型進行轉換即可。
以上這篇Java將對象保存到文件中/從文件中讀取對象的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。