LoginSignup
6
5

More than 3 years have passed since last update.

【Java】カレントディレクトリの取得方法

Posted at

きっかけ

Javaで同階層のファイルを開こうと相対パスを与えたのだが開いてくれなかった
そこで絶対パスを与えてやろうと検索してみたら記事が少なかったので覚書

簡単

あまりにも簡単だから誰も書かないのか
常識の範囲だから書かないのか
わからないけどとっても簡単でした

それがこちら

Dir.java
import java.io.File;

class Dir {
    public static void main(String[] args) {
        String path = new File(".").getAbsoluteFile().getParent();
        System.out.println(path);
        // 例:C:\Users\xxxxx\Documents\java
    }
}

もうひとつ

Dir.java
class Dir {
    public static void main(String[] args) {
        String path = System.getProperty("user.dir");
        System.out.println(path);
        // 例:C:\Users\xxxxx\Documents\java
    }
}

おまけ

Dir.java
import java.io.File;

public class Dir {
    public static void main(String[] args) {
        String path = new File(".").getAbsolutePath();
        System.out.println(path);
        // 例:C:\Users\xxxxx\Documents\java\.
    }
}

.のごみが付きますが置換でやっつ…

けられませんでした
ユーザー名などにピリオド入ってたらいっかんの終わりです。

感謝

散々探してやっとたどり着いたページがこちらです
【Java】カレントディレクトリを取得する

6
5
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
6
5