本文介绍了如何在文件中的特定位置写入内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个名为abhishek.txt的文件,其中包含以下行
Suppose I have a file named abhishek.txt and that contains the following line
我是,你叫什么名字。
I am , and what is your name.
现在我要写
Abhishek
Abhishek
在我之后,就像我是Abhishek,.. 如何直接在此特定位置书写内容。
after "I am" like I am Abhishek, .. How to write the content in this specific position directly.
推荐答案您无法将数据插入文件。您可以使用 RandomAccessFile 覆盖特定位置的数据。但是,插入需要更改其后的所有数据。对于你的情况,尝试这样的事情:
You can't insert data into a file. You can overwrite data at a specific location with RandomAccessFile. However an insert requires changing all of the data after it. For your case try something like this instead:
File file = new File("abhishek.txt"); Scanner scanner = new Scanner(file).useDelimiter("\n"); String line = scanner.next(); String newLine = line.substring(0, 5) + "Abhishek" + line.substring(5); FileWriter writer = new FileWriter(file); writer.write(newLine); writer.close();更多推荐
如何在文件中的特定位置写入内容
发布评论