以对象为单位进行读写文件工具类

//遇到以对象为单位进行读写文件的情况,做记录,源码如下:
package objectio;

import java.io.Serializable;
/**
* 学生类
@version 2018-06-25
@author 踏雪听风呦
*/
@SuppressWarnings("serial")
public class Student implements Serializable {

private String name = null;
private int age = 0;

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 Student(String name, int age) {
super();
this.name = name;
this.age = age;
}

public Student() {
super();
}

@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}


}

package objectio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
* 工具类
@version 2018-06-25
@author 踏雪听风呦
*
*/
public class Util {
/**
* 读取文件中的学生列表

@param uri
*            文件路径
@return 学生列表
*/
@SuppressWarnings("unchecked")
public List<Student> read(String uri) {
List<Student> stulist = null;
InputStream is = null;
ObjectInputStream ois = null;
try {
stulist = new ArrayList<>();
is = new FileInputStream(uri);
ois = new ObjectInputStream(is);
stulist = (List<Student>) ois.readObject();
} catch (FileNotFoundException e) {
System.out.println("要读取的文件未找到哦。");
} catch (IOException e) {
System.out.println("输入流异常。");
} catch (ClassNotFoundException e) {
System.out.println("类未找到异常。");
} finally {
try {
if (is != null)
is.close();
if (ois != null)
ois.close();
} catch (IOException e) {
System.out.println("输入流关闭异常。");
}

}

return stulist;
}

/**
* 将学生列表写到指定文件中

@param uri
*            目标文件路径
@param stulist
*            学生列表
*/
public void write(String uri, List<Student> stulist) {
OutputStream os = null;
ObjectOutputStream oos = null;
try {
os = new FileOutputStream(uri);
oos = new ObjectOutputStream(os);
oos.writeObject(stulist);
} catch (FileNotFoundException e) {
System.out.println("要写出的文件未找到哦。");
} catch (IOException e) {
System.out.println("输出流异常。");
} finally {
try {
if (os != null)
os.close();
if (oos != null)
oos.close();
} catch (IOException e) {
System.out.println("输出流关闭异常。");
}
}
}
}

package objectio;

import java.util.ArrayList;
import java.util.List;

/**
* 程序测试类
@version 2018-06-25
@author 踏雪听风呦
*
*/

public class ObjectReadWrite {

public static void main(String[] args) {
List<Student> stulist = new ArrayList<>();

stulist.add(new Student("赵胜男", 12));
stulist.add(new Student("蒋华月", 23));
stulist.add(new Student("李豆华", 34));
new Util().write("src/student.dat", stulist);

List<Student> readlist = new Util().read("src/student.dat");
for (Student student : readlist) {
System.out.println(student);
}

}
}

猜你喜欢

转载自blog.csdn.net/liyang19951112/article/details/81814746