views:

87

answers:

1

I'm trying to read a file then append some text to a certain place in the file (ie. @ offset jabjab). The problem occurs when i'm trying to write to the file at offset jabjab. what's the error?

File contents:

Mi
<?xml Version="1.0"?>

_

File f = new File("data.dat");
    String brstring = null;
    String entrystring = null;
    try {
        BufferedReader br = new BufferedReader(new FileReader(f));
        String line;
        StringBuilder result = new StringBuilder();
        while ((line = br.readLine()) != null) {
        result.append(line+"\r\n");
        }
        br.close();
        System.out.print(result);
        int jabjab = result.indexOf("?>");
        System.out.println(jabjab);
        PrintWriter fo = new PrintWriter(f);
        fo.write("ok", jabjab, 2);
        fo.flush();
        fo.close();
    } catch (Exception ex) {
        System.out.print(ex.getMessage());
    }

Console output including error:

Mi// output of the result string
<?xml Version="1.0"?>//output of the result string
23//output of jabjab
String index out of range: 25String index out of range: 25//output of exception

Also, after this method is done the original file is now empty...

+3  A: 

I think you've misunderstood the definition of PrintWriter.write(string,offset,length). If I read your question correctly, you think it will write into the output file at that offset. However, the offset specifies where in the string being written to start, so you're trying to write from the string "ok" starting at offset 23. Since the string only has 2 characters you get the exception.

Take a look at java.io.RandomAccessFile if you really want to overwrite specific bytes in a file. Note that, while you can overwrite specific bytes in a file with other bytes, you cannot "insert" data or delete data from a file (resulting in a file of different length) without reading it into memory and writing a new copy to disk.

Jim Garrison