繁体   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();
}

基本上,我使用这个类来做一些事情。 这是在 Tomcat JVM 中运行的应用程序的一部分。 我注意到,无论何时调用此方法,它都会创建一个与参数同名的文件,并且在 raf.close() 之后,它仍然存在。 如何确保删除临时文件?

一个更好的问题是为什么你要经历制作文件的所有麻烦,向文件写入内容,然后删除文件?!

不管你不需要随机访问文件 - FileWriter 会更好。

为了确保文件被删除,按照 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
        }
    }
}

编辑:

您可能还表示,在 Tomcat 进程完成后,文件仍然存在并且您希望它消失。 如果是这种情况,请查看 java.io.File.deleteOnExit()。 当Tomcat JVM存在时,这应该删除文件。

我将假设您只展示了代码的一小部分,并且当似乎没有进行任何随机访问时,您使用RandomAccessFile是有充分理由的。

我会做这样的事情:

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

编辑:我同意,我们不希望 close() 上的理论 IOException 引起问题。 比忽略它更好的是记录“我们从没想过会看到这个......”,但有例外。 我经常创建一个 closeWithoutException() 方法来包装它。 Close 理论上抛出 IOException 似乎是对检查异常的滥用,因为您无法期望调用者做出任何响应。

改用File.createTempFile()吗?

我意识到这不会为您提供与 RandomAccessFile 相同的功能,但您可以在此基础上构建您需要的功能。

实际上,我什至不确定您为什么要将这些东西写入文件。 这是某种使用情况跟踪吗? 为什么不把它存储在内存中?

你试过这个吗?

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

暂无
暂无

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

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