如何在文件中的特定位置写入内容

编程入门 行业动态 更新时间:2024-10-25 12:23:20
本文介绍了如何在文件中的特定位置写入内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

如何在文件中的特定位置写入内容

本文发布于:2023-08-01 04:31:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265236.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位置   文件   内容   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!