下面的代码的主要功能就是删除将原来写入文件的welcome to www.sofencyandalice.top
中的andalice
删除,因为不知道如何在原文件中删除更新,索性先读取存储到字符串中,然后删除文件,再创建文件最后写入新文件中(大佬莫笑),最后更改下文件名
- 在这个过程中就同时遇到了这两个糟糕的情况,刚开始没有写 System.out.println(file.exists());进行判断,自己认为已经删除了,但是后来测试时发现输出结果竟然为true,主要原因就是
在Scanner 进行读取文件流时未关闭即未写change.close()
这样是无法进行删除的因为Scanner进程依旧在使用文件。 - 当写上change.close()时,在控制台输出的
System.out.println(file.delete());//显示false System.out.println(file.exists());//false System.out.println(file);//依旧显示要删除文件的路径
``
- 第一句和第二句本身就是矛盾的这是为神魔 我咨询老师后,老时的原话是
首先,显示原路径不等于删除失败。File封装的就是一个文件路径,不存的文件也可以得到file对象。其次,真的删除失败有很多可能,比如只读文件或者系统文件都删不掉
反应一段时间后恍然大悟,只需要确定file.exists()是false就了可以判断文件已经删除了。
- 重命名失败的主要原因也是如此,读取的文件流或其他进程在占据着文件所以导致无法进行更改名字.
可以仔细看下下面的代码如何实现的,从案例中总结出自己的理解这样理解更深刻
public class deleteStringInFile {
public static void main(String[] args) throws IOException{
//首先创建文件并且在文件中写入数据
File file=new File("D:\\test.txt");
PrintWriter input=new PrintWriter("D:\\test.txt");
input.print("welcome to www.sofencyandalice.top");
input.close();//存储到文件中
Scanner change=new Scanner(file);
String str=change.nextLine();
String str2=str.replaceAll("andalice","");
System.out.println(str2);
change.close();//读取文件流关闭
file.delete();//先删除再创建 效率低暂时未找到其他办法进行更新D:\\poem
System.out.println(file.delete());//删除失败
System.out.println(file.exists());
System.out.println(file);
File file1=new File("D:\\test.txt");
file1.createNewFile();
System.out.println(file1.exists());
PrintWriter input1=new PrintWriter("D:\\test.txt");
input1.print(str2);
input1.close();
//改名
boolean st=file1.renameTo(new File("D:\\Test.txt"));
System.out.println(st);
System.out.println(System.getProperty("user.dir"));//显示文件的
}
}