get File Name from File object - Java java.io

Java examples for java.io:File Name

Description

get File Name from File object

Demo Code

//package com.java2s;
import java.io.File;
import java.util.regex.Pattern;

public class Main {
    public static String getFileName(File file) {
        String filename;/* w  w w . j  a v a2  s.c  o  m*/
        String[] parts = file.toString().split(Pattern.quote("\\"));
        filename = parts[parts.length - 1]; //filename including extension

        String[] segs = filename.split(Pattern.quote("."));
        filename = segs[segs.length - 2];

        return filename;
    }

    public static String getFileName(String filename) {
        String[] parts = filename.toString().split(Pattern.quote("\\"));
        filename = parts[parts.length - 1]; //filename including extension      
        String[] segs = filename.split(Pattern.quote("."));
        filename = segs[segs.length - 2];
        return filename;
    }
}

Related Tutorials