Read a file and replace certain line with a new one

时间:2017-10-12 09:38:29

标签: java-8

I want to:

  • Read a file,
  • Find a line that starts with certain word
  • Replace that line with a new one

Is there an efficient way of doing this using Java 8 Stream please?

1 个答案:

答案 0 :(得分:0)

Can you try this sample program. I read a file and look for a pattern, if I find a pattern I replace that line with a new one.

In this class: - In method getChangedString, I read each line (Sourcefile is the path to the file you read) - using map I check each line - If I find the matching line, I replace it - or else I leave the existing line as it is - And finally return it as a List

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class FileWrite {

    private static String sourceFile = "c://temp//data.js";
    private static String replaceString = "newOrders: [{pv: 7400},{pv: 1398},{pv: 1800},{pv: 3908},{pv: 4800},{pv: 3490},{pv: 4300}";

    public static void main(String[] args) throws IOException {
        Files.write(Paths.get(sourceFile), getChangedString());
    }

    /*
     * Goal of this method is to read each file in the js file
     * if it finds a line which starts with newOrders
     *  then it will replace that line with our value
     * else 
     *  returns the same line
     */
     private static List<String> getChangedString() throws IOException {
        return Files.lines(Paths.get(sourceFile)) //Get each line from source file
                //in this .map for each line check if it starts with new orders. if it does then replace that with our String
                .map(line -> {if(line.startsWith("newOrders:" )){
                    return replaceString;
                } else {
                    return line;
                }
                        } ) 

                //peek to print values in console. This can be removed after testing
                .peek(System.out::println)
                //finally put everything in a collection and send it back
                .collect(Collectors.toList());



    }
}
相关问题