@@ -29,7 +29,7 @@ public class FilesAndStreams {
2929 //----helpers:
3030
3131 /**
32- * Generic class to give line operations as lambda expressions.
32+ * Generic class to define line operations as lambda expressions.
3333 */
3434 public static interface LineOperation {
3535 /**
@@ -229,7 +229,7 @@ public static boolean replaceLineInFile(String pathWithName, String lineMatchReg
229229 * @return true (all good), false (error during read/write or line not found)
230230 */
231231 public static boolean replaceLineInFile (String pathWithName , String lineMatchRegExp , LineOperation lineOperation ){
232- try {
232+ try {
233233 Path path = Paths .get (pathWithName );
234234 List <String > fileContent = new ArrayList <>(Files .readAllLines (path , StandardCharsets .UTF_8 ));
235235 boolean foundLine = false ;
@@ -248,8 +248,44 @@ public static boolean replaceLineInFile(String pathWithName, String lineMatchReg
248248 }else {
249249 throw new RuntimeException ("Line matching regular expression NOT found in: " + pathWithName );
250250 }
251-
252- } catch (IOException e ) {
251+ }catch (IOException e ){
252+ e .printStackTrace ();
253+ return false ;
254+ }
255+ }
256+ /**
257+ * Open a file, search line by regular expression then modify line by custom operation and store modifications.
258+ * Stops after first match. If the line is not found append it ('oldLine' parameter will be empty string in this case).
259+ * @param pathWithName - path to file including file-name
260+ * @param lineMatchRegExp - regular expression to find line
261+ * @param lineOperation - modify or create line with {@link LineOperation} (use lambda expression, e.g.: (oldLine) -> { return newLine });
262+ })
263+ * @return true (all good), false (error during read/write)
264+ */
265+ public static boolean replaceLineOrAppend (String pathWithName , String lineMatchRegExp , LineOperation lineOperation ){
266+ try {
267+ Path path = Paths .get (pathWithName );
268+ List <String > fileContent = new ArrayList <>(Files .readAllLines (path , StandardCharsets .UTF_8 ));
269+ boolean foundLine = false ;
270+ for (int i =0 ; i <fileContent .size (); i ++) {
271+ String line = fileContent .get (i );
272+ if (line .matches (lineMatchRegExp )) {
273+ foundLine = true ;
274+ String newLine = lineOperation .run (line );
275+ fileContent .set (i , newLine );
276+ break ;
277+ }
278+ }
279+ if (foundLine ){
280+ Files .write (path , fileContent , StandardCharsets .UTF_8 );
281+ return true ;
282+ }else {
283+ String newLine = lineOperation .run ("" );
284+ fileContent .add (newLine );
285+ Files .write (path , fileContent , StandardCharsets .UTF_8 );
286+ return true ;
287+ }
288+ }catch (IOException e ){
253289 e .printStackTrace ();
254290 return false ;
255291 }
0 commit comments