编写java程序,往一个txt文件里写入学生的基本信息,然后再读出这些信息并打印出来,最后把该文件拷贝到指

2024-11-19 06:21:34
推荐回答(1个)
回答(1):

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
* 编写java程序,往一个txt文件里写入学生的基本信息,然后再读出这些信息并打印出来,
* 最后把该文件拷贝到指定位置并在文件名前加入日期信息进行备份。
* @author Jr
*
*/
public class IOStudent {
private static void writeObject(Object obj, String path) throws IOException {
ObjectOutputStream oos = null; // 从ObjectOutputStream这个名字就可以看出,这个类是专门针对对象进行写入的
try {
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
oos.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
} finally {
oos.close(); // 写完一定要关,不然扣100工资
}
}
private static Object readObject(String path) throws Exception {
Object obj = null;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));
obj = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
ois.close(); // 读完也要关.
}
return obj;
}
public static void main(String[] args) throws Exception {
Student student = new Student();
student.setStudentId(731);
student.setName("五道杠");
student.setAge(13);
writeObject(student, "d:/obj.txt");
//上面对student对象写入obj.txt了
//---------------------------------
//下面开始把对象从obj.txt中读出
Student newStudent = (Student)readObject("d:/obj.txt"); // 这里需要吧Object类型强转为Student类型
System.out.println("学号是:" + newStudent.getStudentId());
System.out.println("姓名是:" + newStudent.getName());
System.out.println("年龄是:" + newStudent.getAge());
}
}