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.

有帮助吗?

解决方案 2

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top