java将多个文件写入到一个文件流中再有规律的取出_编写java程序,往一个txt文件里写入学生的基本信息,然后再读出这些信息并打印出来,最后把该文件拷贝到指...

满意答案

02ae427d08e371d7e90d5b995e828d6d.png

azonyb

2014.02.18

02ae427d08e371d7e90d5b995e828d6d.png

采纳率:59%    等级:12

已帮助:13223人

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());

}

}

22分享举报

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值