Reputation: 379
I have a file that my scanner reads, then in a new file my writer copies some part of it, and replaces the lines I want to edit.
I have a problem in some specific lines, to which I want to add some elements from a stringarray [Ddd,Eee,...]
.
My problem is that I can't get the scanner and the filewriter to identify the exact position I want to transfer the elements. They need to be below "downstream_rm"
, between / and / , and also they need to replace the old text.
Example/Target:
Old file lines:
....
downstream_rm(j,l) ...
/ Aaa.(bbb)
Bbb.(ccc) /
....
New file lines:
...
downstream_rm(j,l( ....
/ str1
str2
... /
This code I tried, but didnt get the desired results cause it also keeps the old text:
public static void main(String[] args) {
File file = new File();
File filenew = new File();
try {
PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains("downstream_rm(j,l)")) {
scanner.nextLine(); // so that the line with "downstream" wont be deleted
String raw = "" ;
for (int index = 0; index < strarray.size(); index++) {
String s = strarray.get(index);
raw = raw + "\n" + s;
}
line = "/"+raw+"/" ; }
out.write(line);
out.write("\n");
}
out.flush();
out.close();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Also tried this, but it didnt print anything new:
if(line.contains("downstream_rm(j,l)")){
scanner.nextLine();
String raw = "" ;
for (int index = 0; index < strarray.size(); index++) {
String s = strarray.get(index);
raw = raw + "\n" + s;
}
String raw2 = raw.replaceAll(",", "");
line = line.replaceAll("/.*?/", "/"+raw2+"/");
}
out.write(line);
out.write("\n");
Upvotes: 0
Views: 122
Reputation: 1785
your code is not doing what it should because in line
line = line.replaceAll("/.*?/", "/"+raw2+"/");
string from reference "line" doesn't match regex, therefore it doesn't replace
here is what your need
if (line.contains("downstream_rm(j,l)")) {
String replacement = line;
while (!replacement.matches(".*?/.*?/.*?")) {
replacement += scanner.nextLine();
}
String raw = "";
for (int index = 0; index < strarray.size(); index++) {
String s = strarray.get(index);
raw = raw + "\n" + s;
}
String raw2 = raw.replaceAll(",", "");
line = replacement.replaceAll("/.*?/", "/" + raw2 + "/");
}
just make sure your "raw2" variable points to right String object, and in result variable line will contain replaced string
Upvotes: 2