简体   繁体   English

删除方法不删除 - Java

[英]Delete method doesn't delete - Java

I made a program that can display and edit a record.我制作了一个可以显示和编辑记录的程序。 The problem is that I cannot delete the file that I wanted to delete to replace it with the edited ones.问题是我无法删除要删除的文件以将其替换为已编辑的文件。

public class Laboratory {



public static void main(String[] args) throws FileNotFoundException,InterruptedException,IOException {
    
// paste your script here ;)
    
    String fileName = "record.txt";
    String filepath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + fileName;
    
    String in = "";
    File file = new File(filepath);
    Scanner fscan = new Scanner(file);
    Scanner scan = new Scanner(System.in);
    PrintWriter pw = null;
    int linecount = 1;
    
    String content = "";
    
    // reads the file according to the given line count.
    
    for(int i = 0; i < linecount; i++) {
        
        content = fscan.nextLine();
        
    }
    
    // creates the template file.
    
    String tempPath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + "temp.txt";
    
    String contentParts[] = content.split("\\|");
    
    System.out.println(content);
    System.out.println(contentParts[1]);
    System.out.println(contentParts[2]);
    
    System.out.print("change the name >> ");
    in = scan.nextLine();
    
    // edits the scanned content from the file.
    
    String finalContent = "|" + in + "|" + contentParts[2];
    
    System.out.println(finalContent);
    
    
    file = new File(filepath);
    fscan = new Scanner(file);
    
    // scans the original record and pastes it in a new template file.
    
    try {
        
        pw = new PrintWriter(new FileOutputStream(tempPath));
        
        if(linecount == 1) {
                
                content = fscan.nextLine();
                pw.println(finalContent);
                
                while(fscan.hasNextLine()) {
                    
                    content = fscan.nextLine();
                    pw.println(content);
                    
                }
                
        }
        
        else if (linecount > 1) {
            
            for (int i = 0; i < linecount - 1; i++) {
                
                content = fscan.nextLine();
                pw.println(content);
                
            }
            
            pw.println(finalContent);
            content = fscan.nextLine();
                
            while (fscan.hasNextLine()) {
                
                content = fscan.nextLine();
                pw.println(content);
                
            }
            
            
            
        }
        
        
        
    }
    
    catch(FileNotFoundException e) {
        
        System.out.println(e);
        
    }
    
    finally {
        
        pw.close();
        fscan.close();
        
    }
    
    
    
    // deletes the original record
    
    file.delete();
    
} // end of method

} // script test class end

Although, I made a test program that successfully deletes a file.虽然,我制作了一个成功删除文件的测试程序。

public class delete {

public static void main(String[] args) {
    
    Scanner scan = new Scanner(System.in);
    File file = new File("helloworld.txt");
    
    String in;
    
    System.out.println("Press ENTER to DELETE file.");
    in = scan.nextLine();
    
    file.delete();
    

} // main method end

} // program end

My file path is right and I don't really know what causes the problem.我的文件路径是正确的,我真的不知道是什么导致了问题。 Is there a solution to fix this?有解决这个问题的方法吗?

Explanation解释

file.delete() does not throw an error if it failed.如果失败, file.delete()不会抛出错误。 And it failed here, as indicated by its return value being false .它在这里失败了,如它的返回值为false所示。

Execute Files.delete(file.toPath()) instead and you will see the exact error reason, which is:改为执行Files.delete(file.toPath()) ,您将看到确切的错误原因,即:

 Exception in thread "main" java.nio.file.FileSystemException: D:\Programming\Java\Program - Script Test\files\record.txt: The process cannot access the file because it is being used by another process at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:92) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108) at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:274) at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105) at java.base/java.nio.file.Files.delete(Files.java:1146) at Laboratory.main(Laboratory.java:123)

So所以

The process cannot access the file because it is being used by another process该进程无法访问该文件,因为它正被另一个进程使用

Because you still have a scanner to the file open, you are blocking yourself from deleting it.因为您仍然有打开文件的扫描仪,所以您阻止自己删除它。 Close the scanner and it will work.关闭扫描仪,它将工作。


Your code opens two (not one) scanner to file , one at the beginning:您的代码打开两个(不是一个)扫描仪到file ,一个在开头:

Scanner fscan = new Scanner(file);

which you use during your initial loop:您在初始循环中使用的:

for (int i = 0; i < linecount; i++) {
    content = fscan.nextLine();
}

and then later on you create a second one:然后再创建第二个:

fscan = new Scanner(file);

which you also close during your finally block:您在finally块期间也关闭了它:

fscan.close();

But you did never close the first scanner.但是您从未关闭过第一台扫描仪。


Solution解决方案

Add添加

fscan.close();

After the initial loop:在初始循环之后:

for(int i = 0; i < linecount; i++) {
    content = fscan.nextLine();
}
fscan.close();

and the file.delete() will succeed.并且file.delete()将成功。


NIO蔚来

As explained, file.delete() is a poorly designed method.如前所述, file.delete()是一种设计不佳的方法。 Prefer Files.delete(path) .首选Files.delete(path)

In general, if you do not have a good reason to use the old cumbersome file IO library, dont.一般来说,如果您没有充分的理由使用旧的繁琐文件 IO 库,请不要。 Use NIO instead (Java 7+).改用 NIO(Java 7+)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM