Saturday, 15 September 2012

java - Printing a replaced line in a new text file -



java - Printing a replaced line in a new text file -

i trying edit matlabfile , replace of coding parts init in specific lines. however, using format below create changes wont alter line context @ all. (it print same old line). thought doing wrong? 'replaceall' not suitable replace words others in lines?

thanks in advance.

try { printwriter out = new printwriter(new filewriter(filenew, true)); scanner scanner = new scanner(file); while (scanner.hasnextline()) { string line = scanner.nextline(); if (line.contains("stream.values(strmatch('test',stream.components,'exact'))") { string newline = line.replaceall("stream.values(strmatch('test',stream.components,'exact'))", "new data"); out.println(newline); system.out.println(newline); } else { out.write(line); out.write("\n"); } } // while loop out.flush(); out.close(); scanner.close(); } grab (ioexception e) { e.printstacktrace(); }

the replaceall method on string takes regular look argument, , in regular expressions characters have special meanings, such parentheses in expression.

simply utilize replace method instead, takes literal strings:

string newline = line.replace("stream.values(strmatch('test',stream.components,'exact'))", "new data");

don't confused name of method - difference between replace , replaceall not in how many times replace, difference in first 1 takes literal strings , sec 1 takes regular expression. it's in javadoc:

replaces each substring of string matches literal target sequence specified literal replacement sequence.

public string replace(charsequence target, charsequence replacement) {

java java.util.scanner printwriter replaceall

No comments:

Post a Comment