Delete方法不会删除 – Java

huangapple go评论72阅读模式
英文:

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?

英文:

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 = &quot;record.txt&quot;;
String filepath = &quot;D:\\Programming\\Java\\Program - Script Test\\files\\&quot; + fileName;
String in = &quot;&quot;;
File file = new File(filepath);
Scanner fscan = new Scanner(file);
Scanner scan = new Scanner(System.in);
PrintWriter pw = null;
int linecount = 1;
String content = &quot;&quot;;
// reads the file according to the given line count.
for(int i = 0; i &lt; linecount; i++) {
content = fscan.nextLine();
}
// creates the template file.
String tempPath = &quot;D:\\Programming\\Java\\Program - Script Test\\files\\&quot; + &quot;temp.txt&quot;;
String contentParts[] = content.split(&quot;\\|&quot;);
System.out.println(content);
System.out.println(contentParts[1]);
System.out.println(contentParts[2]);
System.out.print(&quot;change the name &gt;&gt; &quot;);
in = scan.nextLine();
// edits the scanned content from the file.
String finalContent = &quot;|&quot; + in + &quot;|&quot; + 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 &gt; 1) {
for (int i = 0; i &lt; 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(&quot;helloworld.txt&quot;);
String in;
System.out.println(&quot;Press ENTER to DELETE file.&quot;);
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?

答案1

得分: 1

file.delete()不会在失败时抛出错误。在这里它失败了,因为其返回值为false

执行Files.delete(file.toPath()),你将看到确切的错误原因,即:

> Exception in thread "main" java.nio.file.FileSystemException: D:\Programming\Java\Program - Script Test\files\record.txt: 由于正在被另一个进程使用,无法访问文件
> 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)

所以

> 由于正在被另一个进程使用,无法访问文件

因为你仍然有一个打开文件的扫描器,你阻止了自己删除它。关闭扫描器就会生效。


你的代码打开了两个(不是一个)扫描器来处理file,一个在开始时:

Scanner fscan = new Scanner(file);

你在初始循环中使用了它:

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

然后稍后你创建了第二个:

fscan = new Scanner(file);

你也在finally块中关闭了它:

fscan.close();

但你从未关闭第一个扫描器。


解决方案

在初始循环之后添加

fscan.close();

像这样:

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

然后file.delete()将成功。


NIO

正如解释所述,file.delete()是一个设计不佳的方法。优先使用Files.delete(path)

一般来说,如果没有充分的理由使用旧的繁琐文件IO库,不要使用它。而是使用NIO(Java 7+)。

英文:

Explanation

file.delete() does not throw an error if it failed. And it failed here, as indicated by its return value being false.

Execute Files.delete(file.toPath()) instead and you will see the exact error reason, which is:

> 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:

Scanner fscan = new Scanner(file);

which you use during your initial loop:

for (int i = 0; i &lt; 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:

fscan.close();

But you did never close the first scanner.


Solution

Add

fscan.close();

After the initial loop:

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

and the file.delete() will succeed.


NIO

As explained, file.delete() is a poorly designed method. Prefer Files.delete(path).

In general, if you do not have a good reason to use the old cumbersome file IO library, dont. Use NIO instead (Java 7+).

huangapple
  • 本文由 发表于 2020年8月4日 01:22:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63234126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定