?? studentfile.java
字號:
//【例9.4】 將若干學(xué)生對象寫入一個(gè)對象文件中。
import java.io.*;
public class StudentFile
{
private String filename;
public StudentFile(String filename)
{
this.filename = filename;
}
public void writeToFile() throws IOException //向指定文件寫入若干學(xué)生對象
{
FileOutputStream fout = new FileOutputStream(this.filename);
ObjectOutputStream objout = new ObjectOutputStream(fout);
objout.writeObject(new Student("楊柳")); //寫入一個(gè)對象
objout.writeObject(new Student("明明"));
objout.writeObject(new Student("小玲"));
objout.close(); //先關(guān)閉對象流
fout.close(); //再關(guān)閉文件流
System.out.println("Write Student to File "+this.filename);
}
public void readFromFile() throws IOException //從指定文件中讀取若干學(xué)生對象
{
FileInputStream fin = new FileInputStream(this.filename);
ObjectInputStream objin = new ObjectInputStream(fin);
System.out.println("readFromFile "+this.filename);
while (true) //輸入流未結(jié)束時(shí)
try
{
Student stu = (Student)objin.readObject(); //讀取一個(gè)對象
System.out.println(stu.toString()+" ");
}
catch (Exception e)
{
break;
}
objin.close(); //先關(guān)閉對象流
fin.close(); //再關(guān)閉文件流
}
public Student[] openFile() throws IOException //返回從指定文件中讀取的學(xué)生對象數(shù)組
{
FileInputStream fin = new FileInputStream(this.filename);
ObjectInputStream objin = new ObjectInputStream(fin);
Student[] students = new Student[20];
int i=0;
while (true)
try
{
students[i] = (Student)objin.readObject(); //讀取一個(gè)對象
i++;
}
catch (Exception e) //捕獲IOException和ClassNotFoundException異常
{
break;
}
objin.close(); //先關(guān)閉對象流
fin.close(); //再關(guān)閉文件流
return students;
}
public static void main(String args[]) throws IOException
{
StudentFile afile = new StudentFile("StudentFile.dat");
afile.writeToFile();
afile.readFromFile();
}
}
/*
程序運(yùn)行結(jié)果如下:
Write Fibonacci to File StudentFile.dat
readFromFile StudentFile.dat
1 楊柳
2 明明
3 小玲
*/
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -