package Login;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectOutTest {
/* 將物件寫入檔案方法 */
public void write(Object o, String path) {
try {
/* 建立存取檔案 */
FileOutputStream fileStream = new FileOutputStream(path);
/* 將存取檔案寫入物件 */
ObjectOutputStream os = new ObjectOutputStream(fileStream);
/* 寫入物件 */
os.writeObject(o);
System.out.println("寫入資料成功");
/* 關閉ObjectOutputStream */
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/* 將物件從檔案中讀出來 */
public void read(String path) {
try {
/* 連線到要讀取的檔案 */
FileInputStream fileStream = new FileInputStream(path);
/* 怎樣讀取連線到的檔案 */
ObjectInputStream os = new ObjectInputStream(fileStream);
/* 讀取物件 */
Dog dog = (Dog) os.readObject();
System.out.println("輸出結果:" + dog.getName() + " is a "
+ dog.getSex() + ",高:" + dog.getHeight() + ",長:"
+ dog.getLength());
/* 關閉物件 */
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/* 往檔案寫入字串 */
public void wirteString(String path, String context) {
try {
/* 建立寫入物件 */
FileWriter fileWriter = new FileWriter(path);
/* 建立緩衝區 */
BufferedWriter writer = new BufferedWriter(fileWriter);
/* 寫入字串 */
writer.write(context);
/* 關掉物件 */
writer.close();
System.out.println("寫入字串成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
/* 讀取檔案中的字串 */
public void readString(String path) {
try {
/* 建立讀取物件 */
FileReader fileReader = new FileReader(path);
/* 建立快取區 */
BufferedReader reader = new BufferedReader(fileReader);
/* 讀取檔案 */
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println("讀取成功:" + line);
}
/* 關閉物件 */
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/* 出函式入口 */
public static void main(String args[]) {
// Dog為外部類必須序列化才能實現它的物件的讀取
Dog d = new Dog();
d.setHeight(12);
d.setLength(23);
d.setName("bobi");
d.setSex('b');
ObjectOutTest qqt = new ObjectOutTest();
qqt.wirteString("F:/IO/cc.sex", "chengchao 123456789");
qqt.readString("F:/IO/cc.sex");
}
}