Lấy đường dẫn của một file trong java (Get the filepath of a file in Java)

Với một file,đôi khi chúng ta muốn lấy thông tin của file như  lấy  đường dẫn của file chẳng hạn thì trong java cung cấp phương thức  File.getAbsolutePath() sẽ cung cấp đầy đủ đường dẫn của một tập tin file.

>> Loạt bài hướng dẫn về file – Xem thêm 

Ví dụ : 

File file = File("C:\\itphutran\\textfile.txt");
System.out.println("Path : " + file.getAbsolutePath());

Sau khi sử dụng phương thức trên thì kết quả sẽ hiện thị đường dẫn đầy đủ:

Path :  C: \\ \\ itphutran\\textfile.txt “.

Tuy nhiên với File.getAbsolutePath()  sẽ lấy đầy đủ đường dẫn file nhưng đôi khi chúng ta chỉ muốn lấy đường dẫn ngang thư mục chứa các file nghĩa là C: \\ \\ itphutran cho nên trường hợp này sẽ sử dụng kết hợp các phương thức như substring ()lastIndexOf (), bạn có thể trích xuất các đường dẫn tập tin một cách dễ dàng:

File file = File("C:\\itphutran\\textfile.txt");
String absolutePath = file.getAbsolutePath();
String filePath = absolutePath.
    substring(0,absolutePath.lastIndexOf(File.separator));

Ví dụ về lấy đường dẫn tập tin và đường dẫn thư mục của file

package com.itphutran.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();

    	}

    }
}
x