Javaでファイルのファイルパスを取得する方法
File.getAbsolutePath()は、ファイルの完全な完全なパス名(filepath + filename)を提供します。
例えば、
File file = File("C:\\abcfolder\\textfile.txt"); System.out.println("Path : " + file.getAbsolutePath());
フルパス「Path : C:\abcfolder\textfile.txt」が表示されます。
ほとんどの場合、ファイルパスを取得する必要があるのは「C:\abcfolder\」だけです。 substring()およびlastIndexOf()の方法を使用すると、ファイルパスを簡単に抽出できます。
File file = File("C:\\abcfolder\\textfile.txt"); String absolutePath = file.getAbsolutePath(); String filePath = absolutePath. substring(0,absolutePath.lastIndexOf(File.separator));
ファイルパスの取得の例
この例では、一時ファイルを作成し、そのファイルパスを出力します。
package com.example.file; import java.io.File; import java.io.IOException; public class AbsoluteFilePathExample { public static void main(String[] args) { try{ File temp = File.createTempFile("i-am-a-temp-file", ".tmp" ); String absolutePath = temp.getAbsolutePath(); System.out.println("File path : " + absolutePath); String filePath = absolutePath. substring(0,absolutePath.lastIndexOf(File.separator)); System.out.println("File path : " + filePath); }catch(IOException e){ e.printStackTrace(); } } }
結果
File path : C:\Users\example\AppData\Local\Temp\i-am-a-temp-file69424.tmp File path : C:\Users\example\AppData\Local\Temp