0

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".

Is there a function for this in Java?

HSP
  • 67
  • 2
  • 11

2 Answers2

3

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 fileName = "file.txt";
String fileContents = loadFile(fileName);
StringBuilder builder = new StringBuilder(fileContents);
String str = "dear";

builder.insert(5, str);

saveFile(fileName, builder.toString()); 
Konrad Botor
  • 4,765
  • 1
  • 16
  • 26
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

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

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • Hi, thanks for the reply. But as I mentioned in the question, I need to insert string directly into my file. Is there any way of doing it without defining a string variable? Something like "insert(file, position, string)". – HSP Jun 26 '18 at 04:57
  • I think (but am not sure) you can use a [`FileChannel`](https://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html) to do so... There is [a question at stackoverflow](https://stackoverflow.com/questions/289965/inserting-text-into-an-existing-file-via-java) with an answer about those. – deHaar Jun 26 '18 at 06:07