Reputation:
Environment : Windows, Java 1.8
I am reading the content of a file and I try to format the lines and remove the tabs, but replaceAll
it's not working.
I tryed with:
BufferedReader bf = FileUtils.getBufferedReader(filePath);
String line;
try {
while ((line = bf.readLine()) != null )
{
if(line.matches(".*=.*"))
{
// this is a simple test scenario
String test = "\tVERSION=version";
test.trim();
test.replaceAll("\t", "");
line.trim();
line.replaceAll("\\t", "");
}
}
} catch (IOException e) {
System.err.println("[ERROR] : Could not read from file <" + filePath + ">!\n");
System.exit(0);
}
I looked into debugger and the tabs are not replaced. On the test scenario I tried with both \t
and \\t
variants without success. Am I doing something wrong?
Upvotes: 0
Views: 34
Reputation: 229158
In Java, a String is immutable - that means you can not change a string, so a method such as String.replaceAll could never change the String object you call that method on.
As noted in the documentation, both String.trim() and String.replaceAll() returns a new, altered, string. That's the string you need to use, and forget about the old string. Your code should look like:
test = test.trim();
test = test.replaceAll("\t", "");
line = line.trim();
line = line.replaceAll("\\t", "");
Upvotes: 1