PrintWriter的例外:字符串索引超出范围
-
16-09-2019 - |
题
我试图读取一个文件然后附加在文件中一些文本到某一个地方(即@偏移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
此外,在此之后方法完成原始文件现在是空...
解决方案
我认为你误解PrintWriter.write(字符串,偏移,长度)的定义。如果我正确地读你的问题,你认为它会写入在该偏移输出文件。然而,偏移指定字符串在被写入启动,所以你想从字符串“OK”写入开始偏移23.自字符串只有2个字符,你得到的异常。
看看java.io.RandomAccessFile中,如果你真的想覆盖特定字节的文件。需要注意的是,当你可以与其他字节的文件覆盖特定字节,你不能“插入”的数据或不读入内存,并写入新的复制到磁盘从文件(导致不同长度的文件)删除数据。
不隶属于 StackOverflow