使用delete()删除文件 - Java [英] Deleting a file using delete() - Java

查看:144
本文介绍了使用delete()删除文件 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码使用 BufferedReader 从文件[main.txt]和 PrintWriter 中读取以写入另一个temp [main.temp]文件。我关闭了这两个流,但是我还是无法在文件对象上使用 delete() main.txt。只有在关闭这两个流之后调用 System.gc()之后,才能删除 File 对象。 p>

 public static boolean delete(String str1,String str2,File FileLoc)
{
File tempFile = null;
BufferedReader Reader = null;
PrintWriter Writer = null;

try
{
tempFile = new File(FileLoc.getAbsolutePath()+.tmp);
Reader = new BufferedReader(new FileReader(FileLoc));
Writer = new PrintWriter(new FileWriter(tempFile));
String lsCurrLine = null; ((lsCurrLine = Reader.readLine())!= null)
{
// ...
// ...

if(true)
{
Writer.println(lsCurrLine);
Writer.flush();
}
}

Reader.close();
Writer.close();
System.gc();

catch(FileNotFoundException loFileExp)
{
System.out.println(\\\
File not found。Exiting);
返回false;

catch(IOException loFileExp)
{
System.out.println(\ n IO Exception when while the record。Exiting);
返回false;
}
}

这可靠吗?或者有没有更好的解决方法? 用户183717 - 你发布的代码显然不是全部的相关代码。例如,那些...和事实 File.delete()实际上并没有在那个代码中调用。



当一个流对象被垃圾收集时,它的终结器关闭了底层的文件描述符。所以,只有在添加 System.gc()调用时,删除才有效,这是强有力的证据,表明您的代码 未能关闭一些流的文件。它可能是一个不同的流对象,在您发布的代码中打开。



正确编写的流处理代码最终使用 块,以确保流无论如何封闭。例如:

 阅读器阅读器=新的BufferedReader(新的FileReader(文件)); 
try {
// do stuff
} finally {
try {
reader.close();
} catch(IOException ex){
// ...
}
}

如果您不遵循这种模式或类似的方式,那么很有可能出现这种情况,即流不会总是被关闭。在你的代码中,例如,如果之一读取写入调用抛出一个异常,您将跳过语句关闭了流。


这是[ie调用 System.gc(); ]可靠吗?

可以将JVM配置为忽略应用程序的 gc()调用。 >

  • 无法保证丢失的数据流将无法访问...

  • 不保证调用 System.gc() 会注意到流不可访问。假设流对象可能是终结的,调用 System.gc()可能只能收集Eden空间。

  • 即使流被发现无法通过GC,不能保证GC将立即运行终结器。假设,运行终结器可以无限期地推迟。




  • 还有更好的解决方法吗?

    是的。修复您的应用程序,以正确关闭它的流。


    My code makes use of BufferedReader to read from a file [main.txt] and PrintWriter to write to a another temp [main.temp] file. I close both the streams and yet I was not able to call delete() method on the File object associated with [main.txt]. Only after calling System.gc() after closing both the stream was I able to delete the File object.

    public static boolean delete (String str1, String str2, File FileLoc)
    {
        File tempFile = null;
        BufferedReader Reader = null;
        PrintWriter Writer = null;
    
        try
        {
            tempFile = new File (FileLoc.getAbsolutePath() + ".tmp");
            Reader = new BufferedReader(new FileReader(FileLoc));
            Writer = new PrintWriter(new FileWriter(tempFile));
            String lsCurrLine = null;
    
            while((lsCurrLine = Reader.readLine()) != null)
            {
                // ...
                // ...
    
                if (true)
                {
                    Writer.println(lsCurrLine);
                    Writer.flush();
                }
            }
    
            Reader.close();
            Writer.close();
            System.gc();
        }
        catch(FileNotFoundException loFileExp)
        {
            System.out.println("\n File not found . Exiting");
            return false;
        }
        catch(IOException loFileExp)
        {
            System.out.println("\n IO Exception while deleting the record. Exiting");
            return false;
        }
    }
    

    Is this reliable? Or is there a better fix?

    解决方案

    @user183717 - that code you posted is clearly not all of the relevant code. For instance, those "..."'s and the fact that File.delete() is not actually called in that code.

    When a stream object is garbage collected, its finalizer closes the underlying file descriptor. So, the fact that the delete only works when you added the System.gc() call is strong evidence that your code is somehow failing to close some stream for the file. It may well be a different stream object to the one that is opened in the code that you posted.

    Properly written stream handling code uses a finally block to make sure that streams get closed no matter what. For example:

    Reader reader = new BufferedReader(new FileReader(file));
    try {
        // do stuff
    } finally {
        try {
            reader.close();
        } catch (IOException ex) {
            // ...
        }
    }
    

    If you don't follow that pattern or something similar, there's a good chance that there are scenarios where streams don't always get closed. In your code for example, if one of the read or write calls threw an exception you'd skip past the statements that closed the streams.

    Is this [i.e. calling System.gc();] reliable?

    No.

    1. The JVM may be configured to ignore your application's gc() call.
    2. There's no guarantee that the lost stream will be unreachable ... yet.
    3. There's no guarantee that calling System.gc() will notice that the stream is unreachable. Hypothetically, the stream object might be tenured, and calling System.gc() might only collect the Eden space.
    4. Even if the stream is found to be unreachable by the GC, there's no guarantee that the GC will run the finalizer immediately. Hypothetically, running the finalizers can be deferred ... indefinitely.

    Or is there a better fix ?

    Yes. Fix your application to close its streams properly.

    这篇关于使用delete()删除文件 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆