標籤:des cti txt 分享 轉換 集合 blog exce tput
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 = new ObjectOutputStream(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 block34 e.printStackTrace();35 }36 catch (IOException e) {//捕獲IO異常37 // TODO Auto-generated catch block38 e.printStackTrace();39 }catch (ClassNotFoundException e) {//捕獲不存在的類型的異常40 41 e.printStackTrace();42 }43 44 45 }46 47 }
運行結果為
存入文本的資料是
JAVA中關於對像的讀寫