0

i am trying to upload zip file which contains only csv file . now i have to validate before fetching file data that directory which i have extracted contains only csv file not any other child folder/directory which contains csv file ?

  • hmmm I think your best shot is to call `listFiles()` and then filter that array, you can be declarative using java streams(needs java 8) or you can do it in a for loop – niceman May 04 '17 at 06:28
  • 1
    `isDirectory` is for checking whether the `File` object is a directory or not, to get the extension you can use apache-commons IO, see here : http://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java – niceman May 04 '17 at 06:30
  • 1
    This can help you: http://stackoverflow.com/questions/1844688/read-all-files-in-a-folder You can then check for the files/directory in the folder – Manuel May 04 '17 at 06:33

3 Answers3

0

You may do it this way:

File rootDir = new File("/my/path/to/exploded/zip/file");
boolean onlyFiles = Arrays.stream(rootDir.list())
                   .allMatch(filename -> new File(rootDir, filename).isFile());

But it only makes sure, all files below your rootDir are files and not directories. You may add another condition to check all files end with a given extension like .csv:

File rootDir = new File("/");
boolean onlyCsvFiles = Arrays.stream(rootDir.list())
                      .allMatch(filename -> new File(rootDir, filename).isFile() &&
                                            filename.endsWith(".csv"));
Harmlezz
  • 7,972
  • 27
  • 35
0

using java 8 you can verify if any of the elements in a path is directory or not: following implementation returns true if a folder is found in the path C:\Foo

String pathString = "C:\\Foo";
Path myPath = Paths.get(pathString);
boolean f = Files.list(myPath).anyMatch(x -> Files.isDirectory(x));
System.out.println(f);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Assuming path is your String.

File file = new File(path);

boolean exists =      file.exists();      // Check if the file exists
boolean isDirectory = file.isDirectory(); // Check if it's a directory
boolean isFile =      file.isFile();      // Check if it's a regular file

Or you can use the NIO class Files and check things like this:

Path file = new File(path).toPath();

boolean exists =      Files.exists(file);        // Check if the file exists
boolean isDirectory = Files.isDirectory(file);   // Check if it's a directory
boolean isFile =      Files.isRegularFile(file); // Check if it's a regular file
Dhiraj Thakur
  • 338
  • 3
  • 11