0

I found a link http://docs.oracle.com/javase/tutorial/essential/io/dirs.html with a example:

    Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
    for (Path name: dirs) {
        System.err.println(name);
    }

Can you help me figure out what I need to do if I want to list a file from "C://" with the above code?

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
NhanHo
  • 3
  • 1
  • 4

4 Answers4

0

With plain Java NIO:

public static void main(final String[] args)
{
    // This will give u all Root Directories. Like: C:, D:, ...
    final Iterable<Path> rootDirs = FileSystems.getDefault().getRootDirectories();

    for (final Path rootDir : rootDirs)
    {
        if (rootDir.startsWith("C:") == false)
            continue;

        // This will loop through every of this root directories
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(rootDir))
        {
            for (final Path file : stream)
            {
                System.out.println(file.getFileName());
            }
        }
        catch (IOException | DirectoryIteratorException x)
        {
            System.err.println(x);
        }
    }

}
d0x
  • 11,040
  • 17
  • 69
  • 104
  • 1
    It will print all the files in all the root folders such as C:\ , d:\, e:\. Put a check for just c drive as question is for that. – Juned Ahsan Aug 09 '13 at 15:45
  • Yes, that is what you asked, or? – d0x Aug 09 '13 at 15:45
  • 1
    I am not the questioner, he/she is asking for "Can you help me how to use it ? if i want to list a file from "C://" with code above" – Juned Ahsan Aug 09 '13 at 15:46
  • I believe, your code will not compile. rootDir is not a string object and hence you cannot do this (rootDir.startsWith("C:") == false) – Juned Ahsan Aug 09 '13 at 15:48
  • NIO Magic :), See: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#startsWith(java.nio.file.Path) – d0x Aug 09 '13 at 15:49
0

try this

 Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
 for (Path name: dirs) {
     System.err.println(name);
    if("C:\\".equalsIgnoreCase(name.toString())){
        File dir = new File(name.toString());
        for(File file : dir.listFiles())
            System.out.println(file.getName());

    }
  }
 }
Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
0

starting java1.7 root directories can be listed using

Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
Robert
  • 5,278
  • 43
  • 65
  • 115
sevvalai
  • 99
  • 2
-1

I perfer just using the File class.

    File[] dirs = File.listRoots();
    for (File name: dirs) {
        if (name.toString().equals("C:\\")){
            String[] cDirs = name.list();
            for (String cDir: cDirs) {
                System.out.println(cDir);
            }
        }
    }

This code with also work in older java versions that Java 1.7; which is the minimum version in order to use FileSystems.

Brinnis
  • 906
  • 5
  • 12