阅读文件,并用新的

问题描述:

我想替换某些行:阅读文件,并用新的

  • 读文件,
  • 查找某些词
  • 开始的行替换该行以一个新的

请问有没有一种使用Java 8 Stream的高效方法?

+0

你尝试过这么远吗?如果可能的话,请添加一些代码并解释你在哪里受困 – MiBrock

你可以试试这个示例程序。我读取一个文件并寻找一个模式,如果我找到一个模式,我用新的模式替换那一行。

在这个类: - 在方法getChangedString,我读每一行(的资源文件的路径为您读取文件) - 使用地图我检查每一行 - 如果我找到匹配的行,我更换 - 否则我离开现有生产线,因为它是 - 最后返回它作为一个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()); 



    } 
} 
+0

谢谢。那很完美。正是我在找什么 –