删除并重命名有问题的文件

时间:2015-04-12 01:30:46

标签: java

我有2个功能,我创建1是更改密码,1是删除文件。所以我的目的是首先运行更改密码功能,然后执行删除文件。代码正常运行并在新文件中创建新密码。但是在尝试删除文件时它不起作用重命名需要一些帮助

public static void replaceAdminPassword()throws IOException{

    try {

        Scanner read = new Scanner(System.in);
        System.out.println("Enter Old Password: ");
        String oldPass = read.nextLine();
        String UserPHash = Utility.getHash(oldPass);
        System.out.println("Enter New Password: ");
        String newPass = read.nextLine();
        String UserNHash = Utility.getHash(newPass);


        read = new Scanner(new File("admin.dat"));
        String line;
        String[] details;
        String input = "";


        File fout = new File("out.dat");
        FileOutputStream fos = new FileOutputStream(fout);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

        while (read.hasNextLine()){
            line = read.nextLine();
            details = line.split("\\|");

            if(details[0].equalsIgnoreCase(UserPHash)){
                input = UserNHash;
                bw.write(input);
                System.out.println("Password Changed.");
            }


        }
        bw.close();
        replaceAdminFile();

    }catch (FileNotFoundException ex){
        System.out.println("file not found");
    }

}

    public static void replaceAdminFile(){
    File oldFile = new File("admin.dat");
    File newFile = new File("out.dat");
    oldFile.delete();
    newFile.renameTo(oldFile);

}

2 个答案:

答案 0 :(得分:2)

我建议改用新的io API:

Files.delete(Paths.get("admin.dat"));
Files.move(Paths.get("out.dat"), Paths.get("admin.dat"));

您可能需要查看movedelete的文档。

不要忘记导入java.nio.file.Filesjava.nio.file.Paths

答案 1 :(得分:0)

您需要通过调用“read.close()”关闭扫描程序,否则文件仍处于打开状态,您无法重命名或删除它。