简体   繁体   English

从(子)目录中的文件读取文本

[英]Read text from file in a (sub)directory

public static String parse(String fileName) throws IOException {
    StringBuilder builder = new StringBuilder();
    String workDir = Paths.get("").toAbsolutePath().normalize().toString();
    String pkgDir = "/src/test/resources/app/testcases/";
    String absoluteFilePath = workDir.concat(pkgDir).concat(fileName);
    Files.lines(Paths.get(absoluteFilePath.replace("\\", "/")), StandardCharsets.UTF_8)
            .forEach(p -> builder.append(p).append(System.lineSeparator()));
    return builder.toString();
}

This works but fileName can be under a subdir of /src/test/resources/ anywhere and I prefer not to hard code app/testcases/ all the time.这有效,但fileName可以在/src/test/resources/的子目录下的任何地方,我不喜欢一直硬编码app/testcases/

Figured it out:弄清楚了:

public String parse(String fileName) throws IOException {
    Path resourcesPath = Paths.get("src", "test", "resources");
    StringBuilder builder = new StringBuilder();
    Path filePath = Files.walk(resourcesPath)
            .filter(p -> p.toFile().isFile()
                    && p.getFileName().toString().equalsIgnoreCase(fileName))
            .findFirst().orElseThrow();
    Files.lines(filePath.toAbsolutePath(), StandardCharsets.UTF_8)
            .forEach(p -> builder.append(p).append(System.lineSeparator()));
    return builder.toString();
}

You can use Path#resolve :您可以使用Path#resolve

public static String parse(String fileName) throws IOException {
    Path absoluteFilePath = Paths.get("/src/test/resources").resolve(fileName);
    StringBuilder builder = new StringBuilder();
    Files.lines(absoluteFilePath, StandardCharsets.UTF_8)
            .forEach(p -> builder.append(p).append(System.lineSeparator()));
    return builder.toString();
}

Or better use a ClassLoader :或者更好地使用ClassLoader

public static String parse(String fileName) throws IOException, URISyntaxException {
    Path absoluteFilePath = Paths.get(Thread.currentThread().getContextClassLoader().getResource(fileName).toURI());
    StringBuilder builder = new StringBuilder();
    Files.lines(absoluteFilePath, StandardCharsets.UTF_8)
            .forEach(p -> builder.append(p).append(System.lineSeparator()));
    return builder.toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM