Skip to content

Commit

Permalink
Java 8 Lambdas and IO
Browse files Browse the repository at this point in the history
  • Loading branch information
bdupreez committed May 26, 2014
1 parent 76c8866 commit 322a6f9
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
6 changes: 6 additions & 0 deletions Java8Musings/pom.xml
Expand Up @@ -30,6 +30,12 @@
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
Expand Down
@@ -0,0 +1,55 @@
package net.briandupreez.blog.java8.io;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
* RecursiveFileLineReader
* Created by Brian on 2014-05-26.
*/
public class RecursiveFileLineReader {

private transient static final Log LOG = LogFactory.getLog(RecursiveFileLineReader.class);

/**
* Get all the non empty lines from all the files with the specific extension, recursively.
*
* @param path the path to start recursion
* @param extension the file extension
* @return list of lines
*/
public static List<String> readAllLineFromAllFilesRecursively(final String path, final String extension) {
final List<String> lines = new ArrayList<>();
try (final Stream<Path> pathStream = Files.walk(Paths.get(path), FileVisitOption.FOLLOW_LINKS)) {
pathStream
.filter((p) -> !p.toFile().isDirectory() && p.toFile().getAbsolutePath().endsWith(extension))
.forEach(p -> fileLinesToList(p, lines));
} catch (final IOException e) {
LOG.error(e.getMessage(), e);
}
return lines;
}

private static void fileLinesToList(final Path file, final List<String> lines) {
try (Stream<String> stream = Files.lines(file, Charset.defaultCharset())) {
stream
.map(String::trim)
.filter(s -> !s.isEmpty())
.forEach(lines::add);
} catch (final IOException e) {
LOG.error(e.getMessage(), e);
}
}


}
@@ -0,0 +1,16 @@
package net.briandupreez.blog.java8.io;

import org.junit.Test;

import java.util.List;

import static org.junit.Assert.*;

public class RecursiveFileLineReaderTest {

@Test
public void testReadAllLineFromAllFilesRecursively() throws Exception {
final List<String> strings = RecursiveFileLineReader.readAllLineFromAllFilesRecursively(".", ".java");
assertFalse(strings.isEmpty());
}
}

0 comments on commit 322a6f9

Please sign in to comment.