簡體   English   中英

用另一個字符串替換File中的行

[英]Replace lines in File with another string

我有一個包含以下內容的文本文件:

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

我有一個數組num [] = {2,3,4}; 其中包含要用此數組中的字符串完全替換的行號

String [] VALUES = new String [] {“AB”,“BC”,“CD”};

即第2行將被替換為AB,第3行將替換為BD,而ine 4將替換為CD。

不在num []數組中的行必須與所做的更改一起寫入新文件。

到目前為止我有這個。我嘗試了幾種循環,但它仍然不起作用。

public class ReadFileandReplace {

/**
 * @param args
 */
public static void main(String[] args) {



    try {



         int num[] = {3,4,5};

         String[] VALUES = new String[] {"AB","BC","CD"};

         int l = num.length;

         FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(fs));

         LineNumberReader reader = new LineNumberReader(br);

         FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");

         String line;
         int count =0;

         line = br.readLine();
         count++;

         while(line!=null){
              System.out.println(count+": "+line);
              line = br.readLine();
              count++;

              int i=0;
                  if(count==num[i]){
                      int j=0;;
                    System.out.println(count);
                    String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
                    j++;
                                            writer1.write(newtext);
                  }
                  i++;
                  writer1.append(line);
              }


    writer1.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    } finally {
    }

}


}

預期輸出應如下所示:

public class MyC{
AB
BC
    CD
    Sys.out.println("hi");
}
}

當我運行代碼時,所有行都出現在同一行。

您將每行附加到相同的字符串。 您還應該在每行的末尾添加行分隔符。 (您可以使用System.getProperty("line.separator")強大地執行此操作)

你差不多完成了,我用地圖更新了你的代碼。 檢查一下

int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};

HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
    lineValueMap.put(num[i],values[i]);
}


FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));

FileWriter writer1 = new FileWriter("test1.txt");

int count = 1;
String line = br.readLine();
while (line != null) {
    String replaceValue = lineValueMap.get(count);
    if(replaceValue != null) {
        writer1.write(replaceValue);
    } else {
        writer1.write(line);
    }
    writer1.write(System.getProperty("line.separator"));
    line = br.readLine();
    count++;
}
writer1.flush();

你沒有附加結束字符。 writer1.append(線); 將數據附加到行而沒有結束字符。 因此它顯示在一行中。 您可能需要將其更改為:writer1.append(line).append(“\\ n”);

嘗試這個

package src;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

public class MainTest {


    static int i ;

    public static void main(String[] arg)
    {
        try {



             int num[] = {3,4,5};

             String[] VALUES = new String[] {"AB","BC","CD"};

             FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
             BufferedReader br = new BufferedReader(new InputStreamReader(fs));

             FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");

             String line;
             Integer count =0;

             line = br.readLine();
             count++;

             while(line!=null){


                 for(int index =0;index<num.length;index++){
                     if(count == num[index]){
                         line = VALUES[index];
                     }
                 }


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

                 line = br.readLine();

                 count++;


                 }


        writer1.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM