java - 清理随机访问文件

标签 java

我有一个代码:

for (int i = 1; i <= Math.ceil(n/m); i++){
  RandomAccessFile file_1 = new RandomAccessFile(".\\src\\dataFiles\\fileC_" + i + ".dat", "r");
  RandomAccessFile index_1 = new RandomAccessFile(".\\src\\dataFiles\\indexC_" + i + ".dat", "r");  

  RandomAccessFile sumFile = new RandomAccessFile(".\\src\\dataFiles\\sumFile_" + i + ".dat", "rw");
  RandomAccessFile sumIndex = new RandomAccessFile(".\\src\\dataFiles\\sumIndex_" + i +".dat", "rw");

  for (int q = 0; q < n; q++){
sumRow = Matrix.getString(file_1, index_1, q).plus(Matrix.getString(tempFile, tempIndex, q));
Matrix.writeLine(sumFile, sumIndex, sumRow);
  }

   tempFile = sumFile;
   tempIndex = sumIndex;    

   file_1.close();
   index_1.close();
}

正如你所看到的,有文件及其索引,它们显示了我在哪里可以找到必要的字符串。 程序的这一部分对文件中的整数进行加法。我可以关闭然后删除“file_1”类型的文件,但“sumFile”类型的文件则不能,因为我对它们使用了引用:

tempFile = sumFile;
tempIndex = sumIndex;

如果我知道如何清理文件,我就不会在每次需要 sumFile 时创建“sumFile”文件。我只会清理它。你知道如何清理RandomAccessFile吗???我知道的唯一方法就是这样做:

File file = new File("path to a sumFile");
file.delete();

然后创建一个具有偶数名称的新文件。

最佳答案

您可以使用RandomAccessFile.setLength(0)截断文件。

关于java - 清理随机访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2420736/

相关文章:

java - 无法从 Java 调用 Perl 脚本

java - 还有什么实现了 JSR-330?

java - Tomcat7 使用 APR 连接器启用 tlsv1.1

java - 我可以在 JpaRepository 的 saveAll 中混合更新和插入吗

Java Math.abs 与 Math.pow

java - 如何在android中注册SmsManager

java - 避免在 h :inputText 中显示默认的 int 值 0

java - 在java中用<br/>替换\n和\r\n

java - JSF 的托管 bean 中的 getter 和 setter 都是强制性的吗?

java - BigInteger 线程安全吗?