Search code examples
javadirectoryfile-read

Acessing folders outside the workspace


I've been searching for an answer to that for a while but without any success. I am trying to load csv files into my program to work with them later on and I have the following issue. When I try to access them directly from the place they are stored on my computer using absolute path :

File folder = new File("C:/Users/trybu/Desktop/AppData");

    File[] listOfFiles = folder.listFiles();

    int filesNo = listOfFiles.length; //and so

it only works if I copy all of those files into my project workspace (I am using Eclipse). But when I change the path name or move files (inside project) to another directory the files won't be read anymore. I find it really weird. Could someone explain that to me and maybe help me finding solution? Thanks!


Solution

  • First of all you need to use a proper path, in your code it looks like a combo of Windows and Unix format but I am not the expert on Windows path formats

    Even better when handling paths and standard folders like the user home folder you can use a system property to get that path. The below code lists all files and folders in (on) the users Desktop

    String homeDir = System.getProperty("user.home");
    
    File desktop = new File(homeDir, "Desktop");
    
    File[] fileList = desktop.listFiles();
    
    for (File file : fileList) {
        System.out.println(file.getName());
    }
    

    This was written and tested on a Mac but works equally well on Windows. Some more info on System property here