我的档案有:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
以下代码执行以下操作。
1.如果行计数等于num[index]
,它将检查该行是否包含来自的字符串
VALUES1[index]
。如果为true,则从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");
}
}
答案 0 :(得分:0)
你应该添加一个指示符来显示该行是否被替换
而(线!= NULL){
boolean exists = false;
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
exists = true;
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
if (!exists)
writer1.write(line+System.getProperty("line.separator"));
答案 1 :(得分:0)
在代码中注释这一行
writer1.write(line+System.getProperty("line.separator"));
然后尝试