Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I get file name and path in java?

I have a zip file in a directory which his name dynamicaly changes. when I click on a button I should be able to get full path of this file plus the name as follow: U:\home\ash\dfi\dfiZipedFile\dfi.zip

public static String getFileFullName(BcfiDownloadPanel bcfiDownloadPanel) {
    File dir = new File("U:\\home\\ash\\dfi\\dfiZipedFile");

    String[] filesList = dir.list();
    if (filesList == null) {
        // Either dir does not exist or is not a directory
    } else {
        for (int i = 0; i < filesList.length; i++) {
            // Get filename of file or directory
            String filename = filesList[i];
        }
    }
    String fileFullName = filesList[0];

    return fileFullName;
}
like image 324
itro Avatar asked Feb 21 '23 11:02

itro


1 Answers

public static String getFirstZipFilename(File dir) {        
    for (File file : dir.listFiles()) {
        String filePath = file.getPath();
        if (file.isFile() && filePath.endsWith(".zip")) {
            return filePath;
        }
    }

    return null;
}
  • Works with any directory (try to make your utility methods generic...)
  • Returns as soon as a valid file has been found (no useless tests)
  • Returns null if nothing was found, so you can know it and display warning messages
like image 55
Aurelien Ribon Avatar answered Mar 05 '23 23:03

Aurelien Ribon