Tuesday 17 March 2020

Get file name from absolute path

Approach 1: Using getName method of File.
File file = new File(filePath);
String fileName = file.getName();

Approach 2: Using getFileName method of Path
Path path = Paths.get(filePath);
String fileName = path.getFileName();

App.java
package com.sample.app;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class App {

    public static String fileName_approach1(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return null;
        }
        File file = new File(filePath);
        return file.getName();
    }

    public static String fileName_approach2(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return null;
        }

        Path path = Paths.get(filePath);
        return path.getFileName().toString();
    }

    public static void main(String args[]) {
        String filePath = "/Users/Shared/data.txt";

        String fileName1 = fileName_approach1(filePath);
        String fileName2 = fileName_approach2(filePath);

        System.out.println(fileName1);
        System.out.println(fileName2);
    }

}

Output
data.txt
data.txt



You may like

No comments:

Post a Comment