我的文件包含:
public class MyC {
public void MyMethod()
{
**System.out.println("My method has been accessed")** // ; is expected
System.out.println("My method has been accessed");
}
}
当我在这个文件上调用 Eclipse 编译器时,它返回:
Code: compiler.err.expected
Kind: ERROR
Line Number: 4
End position: 99
Position: 99
但是,当我尝试插入缺少的字符串“;”时 在第 4 行的位置 99 处,它得到“索引超出范围异常”。
我确实在文件中手动计数,并且文件中甚至不存在索引 99。如何解决此问题。
这是我在特定位置替换的程序:
try {
int num[] = {4}; //Line Numbers
String[] VALUES = new String[] {";"}; //Correct Solutions
//String[] VALUES1 = new String[] {"ic"}; //To Replace With
int [] StartIndex ={99};
int [] EndIndex ={99};
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\MyC1.java");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
String line1 = null;
String done = null;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
boolean exists = false;
for(int index =0;index<num.length;index++){
if(count == num[index]){ //Line Count Equals
exists = true;
StringBuffer buf = new StringBuffer(line);
buf.replace(StartIndex[index], EndIndex[index], VALUES[index]);//Get Positions From Array oF Indexes
done = buf.toString();
writer1.write(done+System.getProperty("line.separator"));
}
}
if (!exists)
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
当我运行上面的程序时,我得到了这个:
该程序运行良好,并且确实替换了特定索引处的字符串。我担心的是为什么 Java 编译器会从文件中返回如此大的位置。