I am currently replacing some strings in a line from a text file. The file has these contents:
public class MyC{
public void MyMethod() {
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
My code is as follow: The program is just replacing string from specific lines defined in an array. I have to keep the original indentation as they were.
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();
}
}
I get this output:

The indentation for CDCD has been lost and it should start from the original position it was in the original text file.
Can someone guide me how to fix this. 1 Tabspace check in the code work fine but how to check for 2 or more tabspaces.
I would convert the println() statement from string to a char[] array & within a loop I check if the current char is an escape character ‘\t’ (a tab).
Lets say that all characters till ‘S’ of …
…are tabs, then the value stored in a variable is equal to the number of tabs & afterwards apply those number of tabs. Remember that when you wrote the ‘Test_File’ you pressed spaces instead of pressing tabs you won’t be able to identify how many tabs are there.
Please compare this code with yours to follow Java conventions.
CODE: