如何使用Java将字符串插入文件中的特定位置? [重复]

时间:2022-09-06 07:38:20

This question already has an answer here:

这个问题在这里已有答案:

Lets say hello.txt contains the string "Hello John". I have a string variable str="dear". I need to insert it directly into the file after Hello i.e. after 5th position. After executing the function file must contain "Hello dear John".

让我们说hello.txt包含字符串“Hello John”。我有一个字符串变量str =“dear”。我需要在Hello之后将其直接插入文件中,即在第5个位置之后。执行函数文件后必须包含“Hello亲爱的John”。

Is there a function for this in Java?

Java中有这个函数吗?

2 个解决方案

#1


2  

You would need to load the entire file as a single String (using one of the methods describe here), then create an instance of StringBuilder from that String and finally use method java.lang.StringBuilder.insert(int dstOffset, CharSequence s) to insert your text and then overwrite the original file with the contents of the builder:

您需要将整个文件作为单个String加载(使用此处描述的方法之一),然后从该String创建StringBuilder的实例,最后使用方法java.lang.StringBuilder.insert(int dstOffset,CharSequence s)插入文本,然后使用构建器的内容覆盖原始文件:

String fileName = "file.txt";
String fileContents = loadFile(fileName);
StringBuilder builder = new StringBuilder(fileContents);
String str = "dear";

builder.insert(5, str);

saveFile(fileName, builder.toString()); 

#2


0  

You could make the hello.txt contain "Hello {TO_BE_REPLACED} John", read that line or the entire file content into a String yourString and then do

您可以让hello.txt包含“Hello {TO_BE_REPLACED} John”,将该行或整个文件内容读入String yourString然后执行

yourString = yourString.replace("{TO_BE_REPLACED}", "Dear");

yourString = yourString.replace(“{TO_BE_REPLACED}”,“亲爱的”);

#1


2  

You would need to load the entire file as a single String (using one of the methods describe here), then create an instance of StringBuilder from that String and finally use method java.lang.StringBuilder.insert(int dstOffset, CharSequence s) to insert your text and then overwrite the original file with the contents of the builder:

您需要将整个文件作为单个String加载(使用此处描述的方法之一),然后从该String创建StringBuilder的实例,最后使用方法java.lang.StringBuilder.insert(int dstOffset,CharSequence s)插入文本,然后使用构建器的内容覆盖原始文件:

String fileName = "file.txt";
String fileContents = loadFile(fileName);
StringBuilder builder = new StringBuilder(fileContents);
String str = "dear";

builder.insert(5, str);

saveFile(fileName, builder.toString()); 

#2


0  

You could make the hello.txt contain "Hello {TO_BE_REPLACED} John", read that line or the entire file content into a String yourString and then do

您可以让hello.txt包含“Hello {TO_BE_REPLACED} John”,将该行或整个文件内容读入String yourString然后执行

yourString = yourString.replace("{TO_BE_REPLACED}", "Dear");

yourString = yourString.replace(“{TO_BE_REPLACED}”,“亲爱的”);