0

So I want to write a String at a specific point in a text file. Should be quite easy but this is my first time using the BufferedWriter class. My source is as follows:

public static String readFile(String fileName) throws IOException {
    String toReturn = "";
    BufferedReader br = null;

    try {
        String sCurrentLine;
        br = new BufferedReader(new FileReader("test.txt"));
        while ((sCurrentLine = br.readLine()) != null) {
            toReturn = toReturn+"\n"+sCurrentLine;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return toReturn;
}

public static void addAfter(String toAdd, char after, String fileName) throws IOException {
    String file = readFile(fileName);
    int length = file.length();
    char[] chr = file.toCharArray();
    boolean pos[] = new boolean[length];
    for(int i = 0; i < length; i++) {
        if(chr[i] == after) {
            pos[i] = true;
        }
    }

    BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
}

I would like to add the String toAdd at position i using the BufferedWriter class. How would I go about jumping to the desired point and writing toAdd?

Thanks in advance

Fraser Price
  • 899
  • 6
  • 15
  • 36
  • `RandomAccessFile` has methods to jump to a particular byte in the file. I think the method is `skipBytes()` or something like that. However, if you are trying to insert text it will be a tad tricky as, by default, file IO is done as an overwrite. What you will have to do is read in the original file from that point on and append it. – CodeChimp Mar 03 '14 at 19:58
  • To do this I think you have to read the contents of the file into a String, create a new String with your edits, and then overwrite the file with your new String. See http://stackoverflow.com/questions/3935791/find-and-replace-words-lines-in-a-file. – ktm5124 Mar 03 '14 at 19:59
  • @ktm5124 Thanks for the link, I've used a similar method to the one described there – Fraser Price Mar 04 '14 at 07:51

2 Answers2

0

One method would be to read the whole text file into memory, modify/replace the line(s) you want to insert into, and then write the strings back out to text file, overwriting the source file.

A somewhat safer method would be to instead write to a second file, then when done saving the output, delete the source file and rename the output file to the source file's name. This would prevent corrupting data if for some reason the write process throws an exception.

Mar
  • 7,765
  • 9
  • 48
  • 82
0

As CodeChimp noted in a comment to your question, all text following an insertion will have to be rewritten to the file. Therefore, your best solution is to open a new temporary file, read the original and copy the text to the new file up to the insertion point, write your new text to the new file, copy the rest of the old file, close both files, delete the original file, and rename the new file. Or, rename the original file to a temporary file name, create a new empty file with the original name of the file to be modified, perform the same copy and insert procedure as above, and then delete the renamed original file. Which of the two options you choose will depend on error handling and whether locks will be used to control concurrent access.

Ned
  • 937
  • 6
  • 10
  • Using indexed file formats, insertion may be much more efficient, but text files are not a form of indexed file. As several other people have suggested, another potentially more efficient option is to skip the temporary file and read the original file into memory inserting the new text at the point it is required and then finish adding the original file contents to the end of the buffer before writing all of it back over the original file. However, that depends very much on the size of the files being updated and may not be any more efficient than the relatively simple method I suggested. – Ned Mar 03 '14 at 22:26
  • @Ned_Nowotny I ended up using a search and replace option. No creation/deletion of files necessary – Fraser Price Mar 04 '14 at 07:58