简体   繁体   English

Java 随机访问文件

[英]Java RandomAccessFile

    public void exportUrlsToFile(String file, String urls) throws IOException {
    String[] urlsArray = urls.split("\\s+");// split on one or more white space characters.

    // create a fresh file
    RandomAccessFile raf = new RandomAccessFile(file, "rw");

    for (String line : urlsArray) {
        line = line.trim();
        if (line.isEmpty()) {// this won't happen!
            continue;
        }
        raf.writeBytes(line);
        raf.writeBytes(newline);
    }
    // close the file handler
    raf.close();
}

Basically, I use this class to do something.基本上,我使用这个类来做一些事情。 This is part of the application that is running inside Tomcat JVM.这是在 Tomcat JVM 中运行的应用程序的一部分。 I have noticed that anytime this method is called, it creates a file with the same name as the argument and after raf.close(), it is still there.我注意到,无论何时调用此方法,它都会创建一个与参数同名的文件,并且在 raf.close() 之后,它仍然存在。 How can I make sure that the temp file is removed?如何确保删除临时文件?

A better question would be why you would want to go through all the trouble of making the file, writing things to the file, and then just delete the file?!一个更好的问题是为什么你要经历制作文件的所有麻烦,向文件写入内容,然后删除文件?!

Regardless you don't need a random access file - a FileWriter would be better.不管你不需要随机访问文件 - FileWriter 会更好。

To ensure that the file is deleted do as Eddie suggests and put the delete in a finnaly block - but you will also need to ensure that the raf.close() IOException is handled... something like:为了确保文件被删除,按照 Eddie 的建议执行并将删除放在最后一个块中 - 但您还需要确保 raf.close() IOException 被处理......类似于:

} finally {
    try
    {
        raf.close();
    }
    catch(final IOException ex)
    {
         // in 14 years of Java programming I still don't know what to do here! ;-)
    }
    finally
    {
        File todelete = new File(file);
        if (!todelete.delete()) {
            // Log a complaint that we couldn't delete the temp file
        }
    }
}

Edit:编辑:

You might also mean that after the Tomcat process finished the file is still there and you want it gone.您可能还表示,在 Tomcat 进程完成后,文件仍然存在并且您希望它消失。 If that is the case look at java.io.File.deleteOnExit().如果是这种情况,请查看 java.io.File.deleteOnExit()。 That should delete the files when the Tomcat JVM exists.当Tomcat JVM存在时,这应该删除文件。

I'm going to assume that you're showing only a small portion of the code and that there's a good reason that you're using RandomAccessFile when it doesn't appear that any random access is being done.我将假设您只展示了代码的一小部分,并且当似乎没有进行任何随机访问时,您使用RandomAccessFile是有充分理由的。

I would do something like this:我会做这样的事情:

public void exportUrlsToFile(String file, String urls) throws IOException {
  String[] urlsArray = urls.split("\\s+");

  // create a fresh file
  RandomAccessFile raf = new RandomAccessFile(file, "rw");

  try {
    for (String line : urlsArray) {
      line = line.trim();
      if (line.isEmpty()) { // this won't happen!
        continue;
      }
      raf.writeBytes(line);
      raf.writeBytes(newline);
    }
  } finally {
    // don't leak file handles on Exception -- put close in "try/finally"
    try { raf.close(); } catch (IOException e) { /* ignore */ }
    File todelete = new File(file);
    if (!todelete.delete()) {
      // Log a complaint that we couldn't delete the temp file
    }
  }
}

EDIT: I agree, we don't want the theoretical IOException on close() to cause problem.编辑:我同意,我们不希望 close() 上的理论 IOException 引起问题。 Better than ignoring it would be to log a "We never expected to see this...." with the exception.比忽略它更好的是记录“我们从没想过会看到这个......”,但有例外。 I often create a closeWithoutException() method just to wrap this.我经常创建一个 closeWithoutException() 方法来包装它。 Close theoretically throwing IOException seems an abuse of checked exceptions because there's nothing you can expect the caller to do in response. Close 理论上抛出 IOException 似乎是对检查异常的滥用,因为您无法期望调用者做出任何响应。

Use File.createTempFile() instead?改用File.createTempFile()吗?

I realize that won't give you the same features as RandomAccessFile but you could build what you need on top of that.我意识到这不会为您提供与 RandomAccessFile 相同的功能,但您可以在此基础上构建您需要的功能。

Actually I'm not even sure why you're writing these things to a file.实际上,我什至不确定您为什么要将这些东西写入文件。 Is this some kind of usage tracking thing?这是某种使用情况跟踪吗? Why not just store it in memory?为什么不把它存储在内存中?

Did you try this ?你试过这个吗?

 File temp = File.createTempFile("file", ".tmp");
 temp.deleteOnExit( );

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

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