import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class IOStreamRW { public static void main(String[] args) throws IOException { //字符—>字節 //Java底層調用FileOutputStream以字節形式寫出數據 //OutputStreamWriter將傳入的字符轉化爲字節 OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream("E:\\a.txt"),"utf-8"); //這裏能夠規定解析時的編碼 ow.write("abcdefgszbjkffasgszbjzxnbzlkzlxzkj"); ow.close(); //字節—>字符 //Java底層調用FileInputStream以字節形式讀取數據 //InputStreamReader將讀取到的字節轉化爲字符 InputStreamReader ir = new InputStreamReader(new FileInputStream("E:\\a.txt")); //定義一個字符數組來存儲讀取到的字節數據 char[] c = new char[10]; int len = -1; //讀取到字節數據後以字符形式輸出 while((len = ir.read(c))!=-1){ System.out.println(new String(c, 0, len)); } ir.close(); } }
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class SerializableDemo { public static void main(String[] args) throws Exception{ //序列化 //對象—>字節 Person p = new Person(); p.setName("伍六七"); p.setAge(18); p.setId("零零柒"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\d.data")); oos.writeObject(p); oos.close(); /* //反序列化 //字節—>對象 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:\\d.data")); //讀取文件中字節數據,而後用ObjectInputStream將字節數據轉換爲對象 Person p = (Person)ois.readObject(); ois.close(); System.out.println(p.getName()); System.out.println(p.getAge()); */ } } //建立Person類提供get_set方法 //一個對象想要被序列化,它所對應的類必須實現Serializable接口 class Person implements Serializable{ //版本號 //沒有手動指定版本號,會自動計算一個版本號 //爲了讓序列化出去的對象能夠反序列回來,須要手動指定版本號,防止類中對象發生改變形成數據丟失 private static final long serialVersionUID = -5209149214681656519L; private String name; private int age; //用static/transient修飾的屬性不會被序列化,不佔內存 //static修飾後自己不須要被序列化,transient則是強制不被序列化 static String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(String id) { this.id = id; } }
注:集合不容許被一次性序列化出去,即一次只能序列化一個對象java