将文件中的字符串从数组替换为行



我的文件有:

 public class MyC{
    public void MyMethod()
    {
        System.out.println("My method has been accessed");
        System.out.println("hi");
    }
}

下面的代码执行以下操作。1. 如果行数等于num[index],它检查该行是否包含字符串fromVALUES1[index]。如果为true,则替换VALUES[index]中第一个索引中的字符串,并写入新文件。

2。如果num索引不等于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");
    }
}

你应该添加一个指示符来显示这一行是否被替换

而(行! = 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"));

注释这行代码

writer1.write(line+System.getProperty("line.separator"));

然后试着

相关内容

  • 没有找到相关文章

最新更新