Java語(yǔ)言只能將實(shí)現(xiàn)了Serializable接口的類的對(duì)象保存到文件中,利用如下方法即可:
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(); } } |
參數(shù)obj一定要實(shí)現(xiàn)Serializable接口,否則會(huì)拋出java.io.NotSerializableException異常。另外,如果寫入的對(duì)象是一個(gè)容器,例如List、Map,也要保證容器中的每個(gè)元素也都是實(shí)現(xiàn) 了Serializable接口。例如,如果按照如下方法聲明一個(gè)Hashmap,并調(diào)用writeObjectToFile方法就會(huì)拋出異常。但是如果是Hashmap<String,String>就不會(huì)出問(wèn)題,因?yàn)镾tring類已經(jīng)實(shí)現(xiàn)了Serializable接口。另外如果是自己創(chuàng)建的類,如果繼承的基類沒有實(shí)現(xiàn)Serializable,那么該類需要實(shí)現(xiàn)Serializable,否則也無(wú)法通過(guò)這種方法寫入到文件中。
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.從文件中讀取對(duì)象
可以利用如下方法從文件中讀取對(duì)象
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; } |
讀取到對(duì)象后,再根據(jù)對(duì)象的實(shí)際類型進(jìn)行轉(zhuǎn)換即可。
以上這篇Java將對(duì)象保存到文件中/從文件中讀取對(duì)象的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。