JAVA中關於對像的讀寫
阿新 • • 發佈:2017-07-10
導入 異常捕獲 ima alt cto exc dex 創建 wid
1 /** 2 * 針對對象的文件讀寫 3 */ 4 5 //導入包 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.FileNotFoundException; 9 import java.io.FileOutputStream; 10 import java.io.IOException; 11 import java.io.ObjectInputStream; 12 import java.io.ObjectOutputStream; 13 import java.util.HashMap;14 15 public class qwe { 16 17 public static void main(String[] args) { 18 try { 19 File f = new File("D:\\Desktop\\NewFile\\hasKey.txt");//關聯文件 20 FileOutputStream wr = new FileOutputStream("D:\\Desktop\\NewFile\\hasKey.txt");//文件寫 21 ObjectOutputStream objw = newObjectOutputStream(wr);//創建對象輸出流 22 FileInputStream re = new FileInputStream("D:\\Desktop\\NewFile\\hasKey.txt");//讀文件 23 ObjectInputStream objr = new ObjectInputStream(re); //創建對象輸入流 24 HashMap<String,String> has = new HashMap<String,String>();//創建集合 25 has.put("001", "hello") ;26 27 objw.writeObject(has);//從對象輸出流中寫入 28 HashMap<String, String> has1 = (HashMap<String, String>) objr.readObject();//從對象輸入流中讀(強制轉換類型) 29 30 System.out.println(has1); 31 32 } catch (FileNotFoundException e) {//無文件異常捕獲 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 } 36 catch (IOException e) {//捕獲IO異常 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 }catch (ClassNotFoundException e) {//捕獲不存在的類型的異常 40 41 e.printStackTrace(); 42 } 43 44 45 } 46 47 }
運行結果為
存入文本的數據是
JAVA中關於對像的讀寫