ファイルパスを取得する Java の方法
Javaでファイルのパスを確認するためにFileクラスを利用します。一般的なメソッドを以下に示します。
- getPath()
File file = new File("C:\\path\\to\\file.txt");
String filePath = file.getPath();
System.out.println(filePath); // 输出:C:\path\to\file.txt
- getAbsolutePath()
File file = new File("C:\\path\\to\\file.txt");
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath); // 输出:C:\path\to\file.txt
- getCanonicalPath()
File file = new File("C:\\path\\to\\file.txt");
String canonicalPath = file.getCanonicalPath();
System.out.println(canonicalPath); // 输出:C:\path\to\file.txt
これらのメソッドが返すパスの文字列は、 オペレーティングシステムによって異なる可能性があることに注意してください。