javaiourifile-uri

URI for a directory path only?


Is it possible to define a URI representing a directory path only (i.e. with no actual file terminating the URI)? Example: file:///path/to/files.

I have the need to specify paths to directories to a Java program and would like to specify them as a URI rather than just a String directory path. The program receiving this information would treat the URI as a directory specifier and expect to read whatever files are contained within. It does not care what the file names are.

UPDATE:

If this is allowed, would I be able to "open" the URI in order to get the listing of files within, and then be able to open them for reading?


Solution

  • Yes it is possible. here's an exemple lets say myfolder is a folder that contains 3 files (file1.txt, file2.txt, file3.txt).

    URI uri = new URI("file:///c:/myfolder/");
    File folder =new File(uri);
    for(File file : folder.listFiles()){
    System.out.println(file.getName()); 
    }
    

    the output will be :

    file1.txt
    file2.txt
    file3.txt