Tuesday, 17 September 2013

Replacing specific line with new line in a .txt file

Replacing specific line with new line in a .txt file

I am trying to edit a text file. My problem is I cant get the new line,
which replaces some part of the old line, to the same position the old
line was located in the file (meaning the same line number). The newline
tends to print out at the bottom of the file. How can I change that?
public static void main(String[] args) {
new class().query();
List<String> strlist = new ArrayList<String>() ;
File file = new File("file");
try {
PrintWriter out = new PrintWriter(new FileWriter(file, true));
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("j(ac)")) {
String raw = "" ;
for (int index = 0; index < strlist.size(); index++) {
String s = strlist.get(index);
raw = raw + "," + s;
}
String raw2 = raw.replaceFirst(",", "");
String newline = line.replaceAll("/.*?/", "/"+raw2+"/");
out.write(newline);
out.close();
}
scanner.close();
} catch (IOException e) {
System.out.println(" Error reading file");
}
}
}

No comments:

Post a Comment