【问题标题】:Java RandomAccessFile Deleting Original textJava RandomAccessFile 删除原文
【发布时间】:2017-01-26 14:01:17
【问题描述】:

所以我使用 RandomAccessFile 在 java 中进行读写。但是当我将字符串写入文件时,文件的当前内容将被覆盖。这是我的代码

    import java.io.RandomAccessFile;
public class hello{
  public static void main(String[] args){
    RandomAccessFile a;
    try{
      a = new RandomAccessFile("a.txt", "rw");
      System.out.println(a.readLine());
      a.writeUTF("another text");
    }
    catch(Exception e){
      e.printStackTrace();
    }
  }
}

这是我的文件内容

101 yes no  yes no
102 no  no  yes no
103 yes no  yes no
104 no  no  yes no
105 no  yes no  no
106 yes yes yes no

但是当我运行程序时它变成了

101 yes no  yes no
another text    no
103 yes no  yes no
104 no  no  yes no
105 no  yes no  no
106 yes yes yes no

我做错了什么?

【问题讨论】:

  • RandomAcessFile#writeUTF 在光标位置开始写入/覆盖内容,并且由于您已经使用a.readLine() 读取了一行,因此您的文件指针位于第二行的开头。完成写入/读取后,最好使用a.close() 关闭文件流。

标签: java file-io randomaccessfile


【解决方案1】:

我不完全确定这是否是您的问题,但我注意到 RandomAccessFile 上有一个 seek 方法,可让您将文件指针移动到文件末尾以进行写入。

【讨论】:

    【解决方案2】:

    你需要找到文件的长度

    long fileLength = a.length();
    

    然后你需要将文件指针偏移到那个位置,这样你就可以写入它了。

    a.seek(fileLength);
    

    这将解决您的问题。 在旁注中,您需要关闭您的资源。也许可以尝试资源:

     try (RandomAccessFile a = new RandomAccessFile("a.txt", "rw")) {
                long fileLength = a.length();
                a.seek(fileLength);
                System.out.println(a.readLine());
                a.writeUTF("another text");
            } catch (Exception e) {
                e.printStackTrace();
            }
    

    【讨论】:

    • 显然取决于您使用的 Java 版本:docs.oracle.com/javase/tutorial/essential/exceptions/…
    • 但是我不能在不覆盖现有行的情况下写入第二行
    • @KidUser 你试过我的修复吗?它将在末尾写下“另一个文本”行。
    • 是的,我试过了,但是文件指针走到了末尾,最后写了“另一个文本”我希望它写在第二行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 2012-05-11
    • 2011-11-24
    • 1970-01-01
    • 2012-01-31
    相关资源
    最近更新 更多