Search code examples
javasharepoint

Java - How to list files on mapped network drive?


Im trying to connect to a mapped drive (sharepoint) to make a list of the files that exists.

So, I have this code that works fine on listing the files on my local PC:

public static void main(String[] args) {
    // Directory path here
    String path = "/"; 

    String files;
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles(); 

    for(int i = 0; i < listOfFiles.length; i++){
        if(listOfFiles[i].isFile()){
            files = listOfFiles[i].getName();
            System.out.println(files);
        }
    }
}

When path = "/", it displays all the files on my local drive C:. Now I would like to know if there is a way to adapt this to list the files of a mapped network drive (mapped as Y: for example).


Solution

  • if your os is windows you can use the \\Server\shared_folder

    public static void main(String[] args) {
        // Directory path here
        String path = "\\\\server\\shared_folder"; 
    
        String files;
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles(); 
    
        for(int i = 0; i < listOfFiles.length; i++){
            if(listOfFiles[i].isFile()){
                files = listOfFiles[i].getName();
                System.out.println(files);
            }
        }
    }
    

    Java 8+;

    import java.io.File;
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            // Directoty path here
            String path = "\\\\server\\shared_folder";
    
            File folder = new File(path);
            File[] listOfFiles = folder.listFiles();
    
            //if (listOfFiles != null) { We can use Stream.ofNullable
                Stream.ofNullable(listOfFiles)
                      .filter(File::isFile)
                      .map(File::getName)
                      .forEach(System.out::println);
           // }
        }
    }