Created
September 22, 2025 12:48
-
-
Save eitch/5079aa833991715e774c1e4e6777b89d to your computer and use it in GitHub Desktop.
PwmTraverse using Files.walk()
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
| ///usr/bin/env jbang "$0" "$@" ; exit $? | |
| import java.nio.file.*; | |
| import java.io.IOException; | |
| public class PwmTraverse { | |
| public static void main(String[] args) throws IOException { | |
| Path root = Paths.get("/sys/class/pwm"); | |
| if (!Files.exists(root)) { | |
| System.err.println("Path does not exist: " + root); | |
| System.exit(1); | |
| } | |
| Files.walk(root).forEach(p -> { | |
| try { | |
| boolean isSymlink = Files.isSymbolicLink(p); | |
| boolean isDirNoFollow = Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS); | |
| if (isSymlink) { | |
| Path linkTarget = Files.readSymbolicLink(p); | |
| Path resolved = (p.getParent() == null ? linkTarget : p.getParent().resolve(linkTarget)).normalize(); | |
| String resolvedKind = kindOf(resolved); // follows to see what it points at | |
| String selfKind = isDirNoFollow ? "dir-symlink" : "file-symlink"; | |
| System.out.println(formatDir(p, isDirNoFollow) + " (" + selfKind + ") -> " + | |
| linkTarget + " (resolves to " + resolved + (resolvedKind.isEmpty() ? "" : ", " + resolvedKind) + ")"); | |
| } else if (isDirNoFollow) { | |
| System.out.println(formatDir(p, true)); | |
| } else { | |
| System.out.println(p.toString()); | |
| } | |
| } catch (IOException e) { | |
| System.out.println(p + " [unreadable]"); | |
| } | |
| }); | |
| } | |
| private static String kindOf(Path path) { | |
| try { | |
| if (Files.isDirectory(path)) return "dir"; | |
| if (Files.isRegularFile(path)) return "file"; | |
| if (Files.exists(path)) return "other"; | |
| return "dangling"; | |
| } catch (Exception e) { | |
| return ""; | |
| } | |
| } | |
| private static String formatDir(Path p, boolean isDir) { | |
| return isDir ? p.toString() + "/" : p.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment