在修改文件内容时出现报错,我的思路是把原文件删了再建个新的文件,然后把修改后的数据装回去,但是出现报错,麻烦指出错误并提出修改建议,谢谢!
private File file;
private ObjectInputStream inputStream = null;
private ObjectOutputStream outputStream = null;
ArrayList<Student> students = new ArrayList<Student>();
public void changeinfo() {
readinfo();
System.out.println("请输入你要修改人的id");
id=gg.get(10000);
int o=0;
int num=0;
for (int i = 0; i < students.size(); i++) {
if(id==students.get(i).getUid()){
o=1;
num=i;
}
}
if (o==0){
System.out.println("查无此人");
}else{
System.out.println("请选择你要修改的信息 1——姓名 2——年龄");
if (gg.get(1,2)==1){
gg.get();
System.out.println("请输入新的姓名");
students.get(num).setName(gg.get());
}else{
System.out.println("请输入新的年龄");
students.get(num).setAge(gg.get(0));
}
System.out.println("修改成功!");
}
try {
file.delete();
file.createNewFile();
inputStream=new ObjectInputStream(new FileInputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
use();
}
public void readinfo(){
try {
inputStream1=new FileInputStream(file);
if(file.length()==0){
System.out.println("文件内无数据!");
inputStream1.close();
}else{
inputStream=new ObjectInputStream(inputStream1);
students=(ArrayList<Student>) inputStream.readObject();
inputStream1.close();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public void use(){
try {
outputStream = new ObjectOutputStream(new FileOutputStream(file));
outputStream.writeObject(students);
System.out.println("添加成功!");
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileOutputStream的默认构造方法是直接覆盖掉原来的文件,而FileOutputStream(File file, boolean append) 的构造方法如果后面的append为true的时候就是追加到尾部而不是直接覆盖了。
你的代码中,打开文件的方式没有指定追加模式,默认采用覆盖模式,所以不用删除原文件,直接打开文件写就可以。