我的文件有:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
下面的代码执行以下操作。1.如果行数相等num[index]
,则检查该行是否包含来自的字符串
VALUES1[index]
。如果为真,它将从第一个索引中替换该字符串VALUES[index]
并写入一个新文件。
2.如果num index不相等num[index]
,它只是将行写入新文件。
我遇到的问题是,在写入新文件后,原来的第 1 行和第 2 行仍然出现在新文件中。如何删除它。
这是我的代码:
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {1,2,4}; //Line Numbers
String[] VALUES = new String[] {"AB","BC","CD"}; //Correct Solutions
String[] VALUES1 = new String[] {"class","void","System"}; //To Replace
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
String line1 = null;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
这是我的结果:
public AB MyC{
**public class MyC{ //This still appears.**
public BC MyMethod()
**public void MyMethod()//This still appears.**
{
CD.out.println("My method has been accessed");
System.out.println("My method has been accessed");
System.out.println("hi");
}
}