Created
April 16, 2025 18:35
-
-
Save bas-kirill/2e92f75995d384c1f32612444becdea3 to your computer and use it in GitHub Desktop.
Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.file.Files | |
import java.nio.file.Path | |
import java.nio.file.attribute.BasicFileAttributes | |
import kotlin.system.exitProcess | |
import kotlin.streams.toList | |
fun main(vararg args: String) { | |
val dir = try { | |
Path.of(args[0]) | |
} catch (_: Exception) { | |
println("The target directory must be specified as the only argument of the application") | |
exitProcess(1) | |
} | |
check(Files.exists(dir)) | |
val result = solution(dir) | |
for ((path, size) in result.fileSizes.entries.sortedBy { it.key }) { | |
println("$path: $size") | |
} | |
println("Total: ${result.totalSize}") | |
} | |
class SolutionResult( | |
val fileSizes: Map<Path, Long>, | |
val totalSize: Long, | |
) | |
private fun solution(dir: Path): SolutionResult { | |
val fileSizes = mutableMapOf<Path, Long>() | |
var totalSize = 0L | |
try { | |
Files.walk(dir).use { paths -> | |
for (path in paths.toList()) { | |
try { | |
val attr = Files.readAttributes(path, BasicFileAttributes::class.java) | |
if (attr.isRegularFile) { | |
val size = Files.size(path) | |
fileSizes[path] = size | |
totalSize += size | |
} | |
} catch (_: Exception) { | |
// Ignore files we cannot access or read | |
} | |
} | |
} | |
} catch (_: Exception) { | |
// Ignore directory read errors | |
} | |
return SolutionResult(fileSizes, totalSize) | |
} |
vladimirlagunov
commented
Apr 17, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment