Common task of a developers is working with files and folders. Finding extension, file name, parent folder and full path can be tricky unless you are prepared. Split and replace can be very handy is such situations.
Below is examples with all possible examples about for getting file name, full file path, file type:
import java.io.File;
public class Files {
public static void main(java.lang.String[] args) {
File file = new File("C:\\PC\\test.txt");
System.out.println("################################" + file + "################################");
System.out.println("get full path: " + file.getPath());
System.out.println("get file name: " + file.getName());
System.out.println("Get folder: " + file.getParentFile());
System.out.println("Get folder 2: " + file.getPath().replace(file.getName(), ""));
System.out.println("Get parent folder: " + file.getParentFile().getName());
System.out.println("Get file type: " + file.getName().split("\\.", 2)[1]);
System.out.println("Get file no extension: " + file.getName().split("\\.", 2)[0]);
}
}
result is:
################################C:\PC\test.txt################################
get full path: C:\PC\test.txt
get file name: test.txt
Get folder: C:\PC
Get folder 2: C:\PC
Get parent folder: PC
Get file type: txt
Get file no extension: test
Read more for String split: Java split string into list examples