How to resolve the algorithm Walk a directory/Non-recursively step by step in the Kotlin programming language
How to resolve the algorithm Walk a directory/Non-recursively step by step in the Kotlin programming language
Table of Contents
Problem Statement
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Walk a directory/Non-recursively step by step in the Kotlin programming language
This Kotlin code reads the files in a directory and filters them using a regular expression.
First, it defines a function walkDirectory that takes a directory path and a regular expression as arguments and returns a list of the files in the directory that match the regular expression.
The function then defines a regular expression r that matches all C header files beginning with 'a'.
Next, the function calls walkDirectory to get a list of all the files in the /usr/include directory that match the regular expression.
Finally, the function prints the list of files to the console.
Source code in the kotlin programming language
// version 1.1.2
import java.io.File
fun walkDirectory(dirPath: String, pattern: Regex): List<String> {
val d = File(dirPath)
require(d.exists() && d.isDirectory())
return d.list().filter { it.matches(pattern) }
}
fun main(args: Array<String>) {
val r = Regex("""^a.*\.h$""") // get all C header files beginning with 'a'
val files = walkDirectory("/usr/include", r)
for (file in files) println(file)
}
You may also check:How to resolve the algorithm Mutual recursion step by step in the Perl programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Ada programming language
You may also check:How to resolve the algorithm Roots of a quadratic function step by step in the Java programming language
You may also check:How to resolve the algorithm Logical operations step by step in the XLISP programming language
You may also check:How to resolve the algorithm SEDOLs step by step in the COBOL programming language