PrintWriter异常:字符串索引超出范围

时间:2009-11-05 05:52:17

标签: java exception printwriter

我正在尝试读取文件,然后将一些文本附加到文件中的某个位置(即@ offset jabjab)。当我试图写入偏移jabjab文件时,会出现问题。什么是错误?

文件内容:

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

控制台输出包括错误:

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

此外,完成此方法后,原始文件现在为空......

1 个答案:

答案 0 :(得分:3)

我认为你误解了PrintWriter.write的定义(字符串,偏移量,长度)。如果我正确地读了你的问题,你认为它会写入该偏移量的输出文件。但是,偏移量指定要写入的字符串中的开始位置,因此您尝试从偏移量23开始写入字符串“ok”。由于字符串只有2个字符,因此您将获得异常。

如果你真的想要覆盖文件中的特定字节,请查看java.io.RandomAccessFile。请注意,虽然您可以使用其他字节覆盖文件中的特定字节,但您无法“插入”数据或从文件中删除数据(导致文件长度不同),而无需将其读入内存并将新副本写入磁盘。

相关问题