Files.lines (Java 8)
如果你是需要按行去处理数据文件的内容,这种方式是我推荐大家去使用的一种方式,代码简洁,使用java 8的Stream流将文件读取与文件处理有机融合。
import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List;
public class readCase {
?? ?public static void main(String[] args) throws Exception { ?? ??? ?readFeatureFiles(); ?? ?}
?? ?public static void readFeatureFiles() throws Exception { ?? ??? ?String path="D:\\Project\\Program";? //文件夹路径 ?? ??? ?List<String> caseNames =new ArrayList<String>(); ?? ??? ?File f = new File(path); ?? ??? ?File[] files = f.listFiles();
?? ??? ?for (int i = 0; i < files.length; i++) { ?? ??? ??? ?System.out.println(files[i].getName()); ?? ??? ??? ?String absPath = files[i].getAbsolutePath();
????????????????// 读取文件内容到Stream流中,按行读取 ?? ??? ??? ?List<String> lines = Files.readAllLines(Paths.get(absPath)); ?? ??? ??? ? ?? ??? ??? ?for (int j = 0; j < lines.size(); j++) { ?? ??? ??? ??? ?String line = lines.get(j); ?? ??? ??? ??? ?if(line.contains("Scenario")) { ?? ??? ??? ??? ??? ?System.out.println(line); ?? ??? ??? ??? ??? ?String caseName = line.substring(line.indexOf(":")+1).trim(); ?? ??? ??? ??? ??? ?caseName = caseName.split(" ")[0].trim(); ?? ??? ??? ??? ??? ?caseNames.add(caseName); ?? ??? ??? ??? ?} ?? ??? ??? ?} ?? ??? ?} ?? ??? ?for (int i = 0; i < caseNames.size(); i++) { ?? ??? ??? ?System.out.println(caseNames.get(i)); ?? ??? ?} ?? ?} }
也可以参考其他方法:
Java读取文件内容的六种方法 - HkGov - 博客园
|