Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

Java File.listFiles() not able to retrieve Names from Absolute Path

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.

Upvotes: 0

Views: 826

Answers (2)

Suganthi
Suganthi

Reputation: 417

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

Upvotes: 1

AlexR
AlexR

Reputation: 115328

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.

Upvotes: 2

Related Questions