如何在文件中的特定位置写入内容 [英] how to write content in a Specific position in a File

查看:87
本文介绍了如何在文件中的特定位置写入内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为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();

这篇关于如何在文件中的特定位置写入内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆