java - 文件未在 Java 中删除
问题描述
这里我做了一个 Java 程序来重命名一个文本文件。我没有使用 renameTo() 方法,因为它只是创建了另一个同名但内容为空的文件。相反,我创建了两个文件对象并尝试将内容从第一个文件复制到第二个文件(如果不存在则创建它),这成功了,但之后当我删除旧文件时它失败了。请让我知道任何答案。这是整个源代码。
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class FileRenamer {
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.println("Enter the name of the text file to be renamed");
String oldname = inp.nextLine();
File oldFile = new File("C:\\Java\\" + oldname + ".txt");
Scanner reader = new Scanner(new File("C:\\Java\\"+oldname+".txt"));
System.out.println("Enter the new File name");
String newname = inp.nextLine();
File newFile = new File("C:\\Java\\"+ newname + ".txt");
if (!newFile.exists()){
newFile.createNewFile();
}
oldFile.renameTo(newFile);
FileWriter newf = new FileWriter("C:\\Java\\"+ newname + ".txt");
while (reader.hasNextLine()) {
String rename = reader.nextLine();
newf.write(rename+"\n");
}
newf.flush();
newf.close();
if (oldFile.delete()){
System.out.println("File renamed");
}
else {
System.out.println("File renaming failed");
}
}catch (Exception e ){
e.printStackTrace();
}
}
}
解决方案
你已经初始化了 oldFile:
File oldFile = new File("C:\\Java\\" + oldname + ".txt");
然后重命名 oldFile:
oldFile.renameTo(newFile);
if (oldFile.delete())
仍然指的是旧路径,该路径不再存在,因为您重命名了文件。(您已经使用 构建了旧路径File oldFile = new File("C:\\Java\\" + oldname + ".txt");
)
推荐阅读
- python - 暴力破解密码
- node.js - 帆默认模型属性何时获取其值?
- sql-server - 平衡数据分发器安装错误
- regex - 如何检测正则表达式中数字前的字符
- r - 将位图格式(例如 PNG)的绘图写入标准输出
- docker - 如何使用 Jenkinsfile 在子目录中构建 Dockerfile
- react-native - 使用 React Native TextInput 编写消息时随机大写锁定
- javascript - 如何使用 jest 在子第三方属性中模拟构造函数
- magento2 - 用于 Google 客户评论的 Magento 2 虚拟主机站点(Google 商家中心)
- c++ - 使用 Makefile 与其他库一起编译 gtk 库