Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3.  
  4. class FileNotDirectoryException extends Exception {
  5.     public FileNotDirectoryException(String message) {
  6.         super(message);
  7.     }
  8. }
  9.  
  10. public class Main {
  11.     public static void main(String[] args) {
  12.         File[] files = (getFilesInFolder("/home/alek/Desktop/"));
  13.         for (File f : files) {
  14.             System.out.println(f.getName());
  15.         }
  16.     }
  17.  
  18.     public static File[] getFilesInFolder(String path) {
  19.         try {
  20.             File f = new File(path);
  21.             if (!f.exists()) {
  22.                 throw new FileNotFoundException("The file \"" + path + "\" doesn't exist.");
  23.             }
  24.             if (!f.isDirectory()) {
  25.                 throw new FileNotDirectoryException("The file \"" + path + "\" isn't a directory.");
  26.             }
  27.  
  28.             return f.listFiles();
  29.  
  30.         } catch (FileNotFoundException | FileNotDirectoryException e) {
  31.             System.err.println(e.getMessage());
  32.         }
  33.  
  34.         return new File[0]; // In case of any errors, an empty list is returned
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement