首页 > 解决方案 > 文件未在 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();
        }

    }
}

标签: java

解决方案


你已经初始化了 oldFile:

File oldFile = new File("C:\\Java\\" + oldname + ".txt");

然后重命名 oldFile:

oldFile.renameTo(newFile);

if (oldFile.delete())仍然指的是旧路径,该路径不再存在,因为您重命名了文件。(您已经使用 构建了旧路径File oldFile = new File("C:\\Java\\" + oldname + ".txt");


推荐阅读