文件的读写类FlieInOut

 

public class f{
eIoutil {//该类只要是给定一个文件名曲读取和写文件
private fileIoutil() {//私有化类防止外部对该类进行修改
}
public static <E> List<E> readfile(String fileName) {//将泛型设为E因为读取文件的类型不一定
// 1把所有用户读取出来,存到List中
ObjectInputStream ois = null;
try {
File file = new File(fileName);//在这里new了个新的文件
ois = new ObjectInputStream(new FileInputStream(file));//读取文件中的内容


@SuppressWarnings("unchecked")
List<E> list = (List<E>) ois.readObject();//将读取的内容放入list中
if (list == null) {//如果读取的内容为空则开一个新的list
list = new ArrayList<E>();
}

 

return list;

 

            //文件存在就读没有就创建一个

} catch (FileNotFoundException e) {
System.out.println("第一次使用用户模块,用户表为空....");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {//finally模块不管出不出异常都会运行的模块,判断文件是否存在关流
try {
ois.close();//流一般在关了第一次后就不可以关第二次了否则会报错
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}

return new ArrayList<E>();//程序运行到这里说明出来异常,为了防止用户那里出错则返回一个新的list
}


public static <E> boolean write(List<E> list, String fileName) {
ObjectOutputStream os = null;//输出流
try {
File file = new File(fileName);
os = new ObjectOutputStream(new FileOutputStream(file));
os.writeObject(list);//将list写入os中
return true;
} catch (IOException e) {
e.printStackTrace();
return false;//写入失败
}finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
}
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值