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.
The problem seems to be with the sourceDirectory. Instead of ~/Documents
, try with the complete path /home/foo/Documents