LoginSignup
3
3

More than 5 years have passed since last update.

java.nio.file.PathのTips

Posted at

文字列からPathをインスタンスを作る

java.nio.file.Paths.get(String first, String... more)を用います。

Path path = Paths.get("/var/temp/sample.csv");
Path path2 = Paths.get("/", "var","temp","sample.csv");

パスの分割記号(Unix系では'/'、Windowsでは'\')は、Java側がうまいこと環境に合わせてくれます。
上記の/var/temp/sample.csvはWindowsではアプリケーションが動いているドライブをルートディレクトリとして解釈してくれます。
たとえば、C:ドライブのどこかでアプリケーションを動かしているのであれば、上記の例はC:\var\temp\sample.csvとなります。
なお、Java 11からはjava.nio.file.Path.of(String first, String... more)が使えます。

// Java11
Path path = Path.of("/var/temp/sample.csv");

パスをつなげる

Path.resolve(Path other)メソッドを用います。

Path parent = Paths.get("/var/temp");
Path child = Paths.get("child");
Path file = Paths.get("sample.csv");
Path connected = parent.resolve(child).resolve(file); // -> /var/temp/child/sample.csv

Paths.get(String first, String... more)を使ってPathインスタンスを作成する場合、/で始めるとルートディレクトリからのパスと見なされてしまします。
なので、うっかり以下のようなコードを書くとうまくいきません。

// /var/temp/childを作りたいとする
Path parent = Paths.get("/var/temp");
Path child = Paths.get("/child"); // "/"から始まっているため、ルートディレクトリからのパスと見なされる
Path connected = parent.resolve(child); // -> /temp

java.io.Fileとの相互変換

Path→File

Path.toFile()メソッドを用います。

Path path = Paths.get("/var/temp");
File file = path.toFile();

File→Path

File.toPath()メソッドを用います。

File file = new File("/var/temp");
Path path = file.toPath();
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3