【发布时间】:2015-07-24 19:58:56
【问题描述】:
我有一个程序来替换文件中的内容。但是会导致IO Exception,不知道逻辑哪里出错了?
代码如下:
import java.io.File;
import java.io.RandomAccessFile;
public class Test
{
public static void main(String args[]) throws Exception
{
File f = new File("test.txt");
replaceAll(f, "hello world", "my world");
}
public static void replaceAll(File file, String oldText, String newText) throws Exception
{
int[] indices = findAllIndices(file, oldText);
if(indices.length > 0)
{
for(int i=0;i<indices.length;i++)
{
replace(file, oldText, newText);
}
}
}
public static int[] findAllIndices(File file, String text) throws Exception
{
int[] indices;
int index = -1, count = 0, i=0;
String givenText = FileUtils.readFileToString(file);
index = givenText.indexOf(text);
while(index >= 0)
{
count++;
index = givenText.indexOf(text, index+1);
}
indices = new int[count];
index = givenText.indexOf(text);
while(index >= 0)
{
indices[i] = index;
index = givenText.indexOf(text, index+1);
i++;
}
return indices;
}
public static void replace(File file, String oldText, String newText) throws Exception
{
int index = findFirstIndex(file, oldText);
if(index >=0)
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(new Integer(index).byteValue());
String emptyString = fixedLengthString(" ", oldText.length());
raf.write(emptyString.getBytes());
raf.seek(new Integer(index).byteValue());
raf.write(newText.getBytes());
}
}
}
MWE 是大代码的一部分。原始代码的堆栈跟踪是:
Exception in thread "main" java.io.IOException: Negative seek offset
at java.io.RandomAccessFile.seek(RandomAccessFile.java:538)
at org.javaextensions.FindAndReplace.replace(FindAndReplace.java:51)
at org.javaextensions.FindAndReplace.replaceAll(FindAndReplace.java:76)
at Test.main(Test.java:16)
Java Result: 1
【问题讨论】:
-
你能发布堆栈跟踪吗?
-
@TomJonckheere 请查看编辑
-
raf.seek(new Integer(index).byteValue()) 中 index 的值是多少?什么时候抛出异常?我认为它是负面的......这会引发 I/O 异常