简体   繁体   English

从指定的相对路径迭代目录中的所有文件

[英]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. 我想使用这种“相对”路径,因为我希望能够将此目录中的所有文件作为github项目的一部分包含在其他人可以下载并运行的项目中。

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. 所以我想在结构中跳起一次../然后进入其中一个目录, word_lists_1并读出所有文件。

6 th 6

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: 所以它不喜欢第49行:

for (File file : fList)

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 . 您可能需要文件规范路径来相应地解析父级,并避免任何未解析的路径,这可能需要一些为null ,因此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. 您可能只需要调整listDirectoryAndFiles(java.nio.file.Path)方法即可满足您的需求。

Note that the aforementioned implementation uses the new I/O capabilities out of Java 7. 请注意,上述实现使用Java 7之外的新I / O功能。

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" 你在当前的执行目录中然后想要遍历一个目录并进入名为“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! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM