Search code examples
javainputstreamtextinputfileinputstream

how to write content in a Specific position in a File


Suppose I have a file named abhishek.txt and that contains the following line

I am , and what is your name.

Now I want to write

Abhishek

after "I am" like I am Abhishek, .. How to write the content in this specific position directly.


Solution

  • 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();