k_rollo
k_rollo

Reputation: 5472

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.

Upvotes: 0

Views: 52

Answers (2)

k_rollo
k_rollo

Reputation: 5472

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();
}

Upvotes: 1

htmoia
htmoia

Reputation: 491

You can use 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:

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();
}

Upvotes: 0

Related Questions