Replace first line of a text file in Java

后端 未结 5 2034
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 03:18

I have a text file where I want to change only the first line of the file. The file could be millions of rows long, so I\'d rather not have to loop over everything, so I\'m

5条回答
  •  轮回少年
    2020-12-11 03:27

    apply a regex only once. String.replaceFirst("regex", "replacementstring") : http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)

    Open the file as RandomAccessFile. Read the 1st line into a string and then apply the change and then write the string back.

提交回复
热议问题