0

Suppose a file contains something like "123456". I want to read it and insert some characters or something between '3' and '4'. Everything I try replaces whole file or append it at the end. here is my code

    File i=new File(path+"names.txt");
    Formatter o=new Formatter(path+"sorted_names.txt");
    Scanner s=new Scanner(i);
    s.useDelimiter(",");

    while(s.Next()!="MyName")
    {


          j++;
        }



    o.format("%s", "Bhargab");
    o.close();

it replaces whole file. I want "Bhargab" written just after "MyName".

  • 2
    Possible duplicate of [Inserting text into an existing file via Java](http://stackoverflow.com/questions/289965/inserting-text-into-an-existing-file-via-java) – ArcticLord Dec 08 '15 at 12:37
  • Think of a file as a fixed array of bytes persisted to external storage. If you wanted to insert N bytes into the middle of an array at point P you would first have to open space by copying all bytes starting at P to the spot P+N, extending the array by N, then you can write new bytes at spot P. You have to do the same with a file, so if it is a small file, read it all in memory, add bytes and write out. If it is a large file, you need a temp file, copy up to P from source file, write new bytes, copy rest of source file, close both, remove original and rename temp back to original. – Jere Dec 08 '15 at 12:43

1 Answers1

0

1 you should specify exactly what rules you want: inserting XXX exactly between each 3 and 4, adding Bhargab after MyName ?

2 read the lines

3 use regex to scan them, and find if it match, which parts, ...

4 or, if you are looking just for a char, use indexOf, ...

5 rewrite your file