2424 *
2525 */
2626public class FilesAndStreams {
27+
28+ //----helpers:
29+
30+ /**
31+ * Generic class to give line operations as lambda expressions.
32+ */
33+ public static interface LineOperation {
34+ /**
35+ * Take line as input and return modified line.
36+ */
37+ public String run (String lineInput );
38+ }
2739
2840 /**
2941 * Collect all data of an InputStream to a string.
@@ -103,14 +115,27 @@ public static boolean writeFileFromList(String pathWithName, List<String> fileCo
103115 }
104116
105117 /**
106- * Open a file, search first line by regular expression, then replace with new line.
118+ * Open a file, search line by regular expression then replace with new line.
107119 * Stops after first match.
108120 * @param pathWithName - path to file including file-name
109121 * @param lineMatchRegExp - regular expression to find line
110122 * @param replacement - complete line is replaced by this
111123 * @return true (all good), false (error during read/write or line not found)
112124 */
113125 public static boolean replaceLineInFile (String pathWithName , String lineMatchRegExp , String replacement ){
126+ return replaceLineInFile (pathWithName , lineMatchRegExp , (oldLine ) -> {
127+ return replacement ;
128+ });
129+ }
130+ /**
131+ * Open a file, search line by regular expression then modify line by custom operation and store modifications.
132+ * Stops after first match.
133+ * @param pathWithName - path to file including file-name
134+ * @param lineMatchRegExp - regular expression to find line
135+ * @param lineOperation - modify line by using this with {@link LineOperation} (use lambda expression)
136+ * @return true (all good), false (error during read/write or line not found)
137+ */
138+ public static boolean replaceLineInFile (String pathWithName , String lineMatchRegExp , LineOperation lineOperation ){
114139 try {
115140 Path path = Paths .get (pathWithName );
116141 List <String > fileContent = new ArrayList <>(Files .readAllLines (path , StandardCharsets .UTF_8 ));
@@ -119,7 +144,8 @@ public static boolean replaceLineInFile(String pathWithName, String lineMatchReg
119144 String line = fileContent .get (i );
120145 if (line .matches (lineMatchRegExp )) {
121146 foundLine = true ;
122- fileContent .set (i , replacement );
147+ String newLine = lineOperation .run (line );
148+ fileContent .set (i , newLine );
123149 break ;
124150 }
125151 }
0 commit comments