Java SE7 Gold 取得を目指して (11)


Java SE7 Gold をとりたい…!

本日は第11回目です。
Java7で大きく変わったNIO.2の前編です。

今日のこぼれ話

本日からNIO.2を勉強しています。
新たに使えるようになったメソッドを見ると便利そうだなーと思うのですが、逆にこれまではどうしていたのでしょうか?
ちょっとしたことを実現するのにも割と面倒なプロセスを踏まざるを得ないような…。
(Javaだから便利なライブラリがあったのでしょうね、きっと)
自分の場合はどうしていたのだろうと考えてみましたが、C#で開発してました。(Windows開発が多いので)
しかしNIO2のおかげでOSの縛りもなくなり選択肢が増えますね!

本日知ったこと(9章 1/2)

  • Path インタフェース

    • Pathオブジェクトの取得
      // 簡易取得
      Path p1 = Paths.get("/temp/dir");
    
      // デフォルト以外のファイルシステムを使う場合はFileSystemクラスから取得
      FileSystem fs = FileSystems.getDefault();
      Path p2 = fs.getPath("/temp/dir2");
    
     Path path = Paths.get(".\\temp\\yyyymmdd\\aaa.txt");
     Iterator<Path> ite = path.iterator();
     while(ite.hasNext()) {
       System.out.println(it.next()); // ルートは返さない
     }
    
    • Path間の相対パスも取得できる
     /*
      ディレクトリ構成
      Parent/
       |- Child1/
        `- Child2/
     */
     Path p1 = Paths.get("Child1");
     Path p2 = Paths.get("Child2");
     System.out.pring(p1.relativize(p2)); // ../Child2
    
  • Files クラス

    • 負けじと便利そう
    • ファイルのメタデータ取得
     Path p1 = Paths.get(".\\sample.txt");
     BasicFileAttributes attr = Files.readAttributes(p1, BasicFileAttributes.class);
     System.out.println(attr.creationTime());
     System.out.println(attr.lastModifiedTime());
     ....
    
    • DOSファイル属性を取得したい場合は DosFileAttributes で取得する
  • ファイルへのランダムアクセス

    • SeekableByteChannelクラスを使用
    • チャネルI/Oはバッファリングするので、ストリームI/Oに比べアクセスが高速
     // 5番目の文字から10文字読み込み
     Path p1 = Paths.get(".\\sample.txt");
     try(SeelableByteChannel ch = Files.newByteChannel(p1)) {
       ByteBuffer buffer = ByteBuffer.allocate(32);
       ch.position(5); // 位置指定
       ch.read(buffer); // 読み込み
       for (int i = 0; i < 10; i++) {
         System.out.print((char)buffer.get(i));
       }
       buffer.clear();
     } catch (IOException ex) {
       e.pringStackTrace();
     }
    

Files.readAllLine() とか、やっと来たか…!って感じですね。