Issue
I am using Files.walk to list all files from a directory, including all levels of sub-directories with a filter for files that end with "java".
public static void main(String[] args) throws IOException {
List<String> files = findFiles(Paths.get("C:\\project"),"java");
files.forEach(System.out::println);
public static List<String> findFiles(Path path, String extension) throws IOException {
List<String> result;
try (Stream<Path> walk = Files.walk(path)) {
result = walk.filter(p -> !Files.isDirectory(p))
.map(p -> p.toString().toLowerCase())
.filter(f -> f.endsWith(extension))
.collect(Collectors.toList());
}
return result;
}
Now I want that string list of files to another method to find a file name with the largest size.
I have no idea how to do it and maybe it was a bad idea to put it in a string list. So I am asking for help or maybe different approach to this problem.
Solution
Try this:
public static void main( final String... args ) throws IOException
{
final var file = findLargestFile( Paths.get( "C:\\project" ),"java" );
System.out.println( file.getAbsolutePath() );
}
public static final File findLargestFile( final Path path, final String extension ) throws IOException
{
try( final var walk = Files.walk( path ) )
{
return walk.filter( p -> !Files.isDirectory( p ) )
.map( Path::toFile )
.filter( f -> f.getName().toLowerCase( ROOT ).endsWith( extension ) )
.max( comparingLong( File::length ) )
.orElse( null );
}
}
findLargestFile() eliminates the files that does not have the right extension, then it gets the largest of the remaining files and returns that, or null if the source folder was empty.
If you want to get back an instance of Path, it may look like this:
public static final Path findLargestPath( final Path path, final String extension ) throws IOException
{
final ToLongFunction<Path> size = p ->
{
var result = 0L;
try
{
result = Files.size( p );
}
catch( final IOException ignored ) {}
return result;
};
final Predicate<Path> validExtension = p -> p.getName( p.getNameCount() - 1 )
.toString()
.toLowerCase( ROOT )
.endsWith( extension );
try( final var walk = Files.walk( path ) )
{
return walk.filter( p -> !Files.isDirectory( p ) )
.filter( validExtension )
.max( comparingLong( size ) )
.orElse( null );
}
}
Instead of swallowing the IOException, you can wrap it into an UncheckedIOException and throw that.
Answered By - tquadrat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.