FileSystemディレクトリのリンクリストの実装

Aug 15 2020

エッジケースを処理するために、既存の実装のメソッドをオーバーライドするラッパークラスをJavaで記述しています。完全な実装は、ここに投稿する必要があるよりも少し複雑なので、支援を要求している部分のみを含む簡略化されたクラスを作成しました。

問題の概要

私は2つのクラスを拡張しています:

「列挙」クラスとして設計された1つのクラスで、他のディレクトリへのシンボリックリンクを含むファイルシステム上のディレクトリを抽象化します。(実世界:「/ sys / block」)。これには2つのメソッドがあります。scan()(リンクされた)サブディレクトリのリストを生成するメソッドと、リストのgetFirst()最初の要素を返すメソッドです。

2番目のクラスは「エントリ」クラスであり、最初のクラスによって列挙されたポイント先のディレクトリを抽象化します。これにはgetName()、ディレクトリのパスを文字列として返すgetNext()メソッドと、次の要素に反復するメソッドの2つのメソッドがあります。

制約

  • JDK8以前との互換性
  • シングルスレッドの使用が想定される場合があります
  • コンストラクターは必要に応じて変更できます。
  • (少なくとも)指定された2つのクラスとそれぞれに2つのメソッドを実装する必要があります。

レビューの焦点

そのscan()方法はここでの私の苦労です。私は2つの方法でソリューションを過度に複雑にしたかもしれないと思います:

  • メソッドtry ... catch内のネストされたブロックscan()は異常に見えます。これを処理する簡単な方法がありませんか?
  • (更新:以下のこの2番目の質問に自己回答しました。)実装されたパターンは明らかに、ArrayList実装を渡すことによって回避している単一リンクリストです。DirEntryそのクラスPathDirEntry nextオブジェクトのみを含むクラスを想像できますが、そのようなリストを生成しようとすると、私が作成した回避策よりもさらに複雑でパフォーマンスが低下するように見えます。
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DeviceList {

    /**
     * Class representing a parent directory which contains symbolic links to other
     * directories
     */
    static class DirEnumerator {

        private Path dirPath;
        private List<DirEntry> entryList = Collections.emptyList();

        public DirEnumerator(String path) {
            dirPath = FileSystems.getDefault().getPath(path);
        }

        /**
         * Scans the directory for entries
         *
         * @return The number of entries found
         */
        public int scan() {
            try (Stream<Path> paths = Files.walk(dirPath)) {
                List<Path> linkedDirs = paths.filter(Files::isSymbolicLink).map(p -> {
                    try {
                        return Files.readSymbolicLink(p);
                    } catch (IOException e) {
                        return p;
                    }
                }).collect(Collectors.toList());
                this.entryList = new ArrayList<>();
                for (int i = 0; i < linkedDirs.size(); i++) {
                    this.entryList.add(new DirEntry(entryList, linkedDirs.get(i), i));
                }
                return this.entryList.size();
            } catch (IOException e) {
                this.entryList = Collections.emptyList();
                return 0;
            }
        }

        /**
         * Gets the first entry in the scanned list
         *
         * @return The first entry if it exists; null otherwise
         */
        public DirEntry getFirst() {
            return entryList.isEmpty() ? null : entryList.get(0);
        }

    }

    /**
     * Class representing a directory
     */
    static class DirEntry {
        private List<DirEntry> entryList;
        private Path path;
        private int index;

        public DirEntry(List<DirEntry> entryList, Path path, int i) {
            this.entryList = entryList;
            this.path = path;
            this.index = i;
        }

        /**
         * Gets the path name of the directory entry
         *
         * @return a string representing the path
         */
        public String getName() {
            return this.path.toString();
        }

        /**
         * Gets the next entry in the list
         *
         * @return the next entry if it exists; null otherwise
         */
        public DirEntry getNext() {
            int nextIndex = index + 1;
            return nextIndex < entryList.size() ? entryList.get(nextIndex) : null;
        }
    }

    public static void main(String[] args) {
        // Test on any directory containing symbolic links to other directories
        DirEnumerator de = new DirEnumerator("/sys/block");
        int n = de.scan();
        System.out.println("Found " + n + " directories.");

        DirEntry e = de.getFirst();
        while (e != null) {
            System.out.println("Directory: " + e.getName());
            e = e.getNext();
        }
    }
}
```

回答

DanielWiddis Aug 16 2020 at 00:27

生成されたパスから逆方向に繰り返すことによってリンクリストを作成するという、2番目の質問を行うためのより簡単な方法を見つけました。

    static class DirEnumerator {

        private Path dirPath;
        private DirEntry first = null;

        // ...

        public int scan() {
            try (Stream<Path> paths = Files.walk(dirPath)) {
                List<Path> linkedDirs = paths.filter(Files::isSymbolicLink).map(p -> {
                    try {
                        return Files.readSymbolicLink(p);
                    } catch (IOException e) {
                        return p;
                    }
                }).collect(Collectors.toList());
                this.first = null;
                int i = linkedDirs.size();
                while (i-- > 0) {
                    this.first = new DirEntry(linkedDirs.get(i), first);
                }
                return linkedDirs.size();
            } catch (IOException e) {
                this.first = null;
                return 0;
            }
        }

        // ...
    }

    static class DirEntry {
        private Path path;
        private DirEntry next;

        public DirEntry(Path path, DirEntry next) {
            this.path = path;
            this.next = next;
        }

       // ...
    }
```