0

我目前正在从文本文件中替换一行中的一些字符串。该文件具有以下内容:

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

我的代码如下:程序只是替换数组中定义的特定行中的字符串。我必须保持原来的缩进。

public class ReadFileandReplace {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
        boolean l1;
        int num[] = {1, 2, 3};
        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("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");

        int count = 1;
        String line = br.readLine();
        while (line != null) {

             l1 = line.contains("\t");
             System.out.println(l1);
            String replaceValue = lineValueMap.get(count);
            if(replaceValue != null) {
                if(l1==true){
                writer1.write("\t"+replaceValue);}
                 writer1.write(replaceValue);
            } else {
                writer1.write(line);
            }
            writer1.write(System.getProperty("line.separator"));
            line = br.readLine();
            count++;
        }
        writer1.flush();
    }
}

我得到这个输出:

输出

CDCD 的缩进已经丢失,它应该从它在原始文本文件中的原始位置开始。

有人可以指导我如何解决这个问题。1 代码中的 Tabspace 检查工作正常,但如何检查 2 个或更多制表位。

4

1 回答 1

1

我会将 println() 语句从字符串转换为 char[] 数组并在循环内检查当前字符是否为转义字符 '\t'(制表符)。

可以说,直到'S'的所有字符......

System.out.println("My method has been accessed"); 

...是选项卡,那么存储在变量中的值等于选项卡的数量,然后应用这些选项卡数量。请记住,当您编写“Test_File”时,您按空格而不是按制表符,您将无法识别那里有多少个制表符。

请将此代码与您的代码进行比较以遵循 Java 约定。

代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
 *
 * @author Deathstar
 */
public class MyC
{ 

public static void main(String[] args)
{

  BufferedReader br = null;

  boolean isLineMatched = false;
  int c1 = 0, lineNumArrLength, lineCount = 0;
  int lineNums[] = {1,2};
  char[] toCharArr;
  String sCurrentLine, oldText, addSpaces = "";
  String[] valuesToOverwrite = new String[] {"AB","BC","CD"};

    try 
    {

      lineNumArrLength = lineNums.length;

      br = new BufferedReader(new FileReader("C:\\Users\\jtech\\Documents\\NetBeansProjects\\HelpOthers\\src\\textFiles\\Test_File.txt"));

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

      for (int i = 0;i < (valuesToOverwrite.length -1) ;i++ ) //Loop 3 Times
      { 
          writer1.append(valuesToOverwrite[i]+System.lineSeparator()+System.lineSeparator());
      }

      while ((sCurrentLine = br.readLine()) != null )
      {
          oldText = sCurrentLine; 
          lineCount++;        
          isLineMatched = false;      
          toCharArr = sCurrentLine.toCharArray();

          while (c1 < lineNumArrLength) 
          {
              if (lineCount == lineNums[c1])   
              {
                for (int c2 = 0; c2 < toCharArr.length; c2++)
                {
                    if (toCharArr[c2] == ' ')
                    {
                        addSpaces += " ";
                    }
                }
                      String newText = sCurrentLine.replace(oldText, addSpaces+valuesToOverwrite[lineCount]);
                      writer1.append(newText+System.lineSeparator());
                      isLineMatched = true;
                      addSpaces = "";
              } 
              c1++; 

          }

          if (isLineMatched == false)
          {
            writer1.append(oldText+System.lineSeparator());
          }

          c1 = 0;
      }




      writer1.close();


    } 
    catch (IOException e) 
    {
      e.printStackTrace();
    } 
    finally 
    {
      try 
      {
        if (br != null)
        {
              br.close();
        }
      } 
      catch (IOException ex) 
      {
        ex.printStackTrace();
      }
    }    
  }        

}
于 2013-01-08T19:34:06.940 回答