Question

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

No correct solution

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top