Question

import java.io.File;

public class FileDemo {

public static void main(String[] args) {

    String sourceDirectory = "~/Documents";

    System.out.println(sourceDirectory);

File dir = new File(sourceDirectory);

        File[] dirFiles = dir.listFiles();
        for (File file : dirFiles)
        {
                System.out.println( file.getName() );
        }
   }
}

I am using the code above to list files in the Documents directory in Ubuntu. The same code works if I replace the folder name to a local folder where the Java class file resides. HOwever, I always get NULL Pointer exception when using absolute paths, as the dirFiles is NULL.

Could someone explain if there is any mistake in my approach.

Thanks.

Was it helpful?

Solution 2

The problem seems to be with the sourceDirectory. Instead of ~/Documents , try with the complete path /home/foo/Documents

OTHER TIPS

Tilda ~ is not absolute path. It is a feature of typical unix shell to replace it by home directory of current user. In java program you should use System.getProperty ("user.home") instead of tilda.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top