smatthewenglish
smatthewenglish

Reputation: 2889

Iterate over all files in directory from a specified relative path

I want to use this kind of "relative" path, because I want to be able to include all the files in this directory as part of a github project that others can download and just run.

So I want to just jump up once in the structure ../ and then go down into one of the directories there, word_lists_1 and read out all the files.

6th

This code keeps crashing though. Why is that?

public static void main(String[] args)
{
    ArrayList<File> arrayList = new ArrayList<File>();

    final String directoryName = "../word_lists_1";
    listf( directoryName, arrayList );

    for(File elem : arrayList)
    {
        System.out.println(elem+"  ");
    }

}

public static void listf(String directoryName, ArrayList<File> files)
{
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList)
    {
        if (file.isFile())
        {
            files.add(file);
        }
        else if (file.isDirectory())
        {
            listf(file.getAbsolutePath(), files);
        }
    }
}

This is the error message:

Exception in thread "main" java.lang.NullPointerException
at Main.listf(Main.java:49)
at Main.main(Main.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

so it doesn't like line 49 which is this:

for (File file : fList)

Upvotes: 4

Views: 3746

Answers (2)

tmarwen
tmarwen

Reputation: 16364

You may need the file canonical path to resolve the parent accordingly and avoid any path to be unresolved which may need to a some being null, hence the NullPointerException.

One simple implementation to resolve the a directory out of a realtive path to the current directory then display of load its tree hierarchy would be as follows:

public class Main
{
    public static void main( String[] args ) throws URISyntaxException, IOException
    {

        File currentDir = new File( "." ); // Read current file location
        File targetDir = null;
        if (currentDir.isDirectory()) {
            File parentDir = currentDir.getCanonicalFile().getParentFile(); // Resolve parent location out fo the real path
            targetDir = new File( parentDir, "word_lists_1" ); // Construct the target directory file with the right parent directory
        }
        if ( targetDir != null && targetDir.exists() )
        {
            listDirectoryAndFiles( targetDir.toPath() );
        }
    }

    private static void listDirectoryAndFiles( Path path ) throws IOException
    {
        DirectoryStream<Path> dirStream = Files.newDirectoryStream( path );
        for ( Path p : dirStream )
        {
            System.out.println( p.getFileName() );
            if ( p.toFile().isDirectory() )
            {
                listDirectoryAndFiles( p );
            }
        }
    }

}

You may just need to adjust the listDirectoryAndFiles(java.nio.file.Path) method to meet your needs.

Note that the aforementioned implementation uses the new I/O capabilities out of Java 7.

Upvotes: 3

Vihar
Vihar

Reputation: 3831

This is what I understand from your requirements

  • you are in current execution directory and you then want to traverse back one directory and get into some other folder by the name "word_lists_1"

if I understand your question correctly ,I would have implemented it like

String str=System.getProperty("user.dir");
String filePath = str+"/../word_lists_1";

if you are in some other directory then you can do

String str=Paths.get(".").toAbsolutePath().normalize().toString();
String filePath = str+"/../word_lists_1";

hope this helps!

good luck!

Upvotes: 1

Related Questions