How do I distinguish between a file and a folder when renaming a file/folder in java

81 Views Asked by At

I am currently programming a file name normaliser. Files have a format and folders dont. When I rename a file I need to make sure that I do not affect the format therefore I did

fileName.substring(fileName.lastIndexOf("."),fileName.length) 

thereby if I want to replace all the periods in a fileName it does not affect the format, when a folder with periods in its name goes through this process, the last instance of the period is still part of its name, therefore it does not replace all the dots in the folders name. I need to know how to distinguish between a file and a folder so I can fix this.

2

There are 2 best solutions below

0
On BEST ANSWER

You can use

someFile.isDirectory();

It returns true if the file is a folder, and false if not.

0
On

You can use File.isDirectory() to test whether the file denoted by this abstract pathname is a directory. You can also use File.isFile() to test whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria.

File f = new File(fileName);
if (f.isFile()) {
  // it's a file.
} else if (f.isDirectory()) {
  // it's a directory.
}