java深入列出目录并进行操作

时间:2018-04-22 09:10:02

标签: java file

我正在尝试在包含一些子文件夹的目录中进行一些文件编辑。但是我的java应用程序并不深入子文件夹,只能在第一个子文件夹中进行操作,如下所示

Folder1(有效) -folder11(作品) --files(作品) --folder111(不起作用) -folder12(作品) --files(作品) -folder13(作品) --files(作品)

我做错了什么?

这是我的代码:

      new FloatingActionButton(
        onPressed: () {
          getImage(ImageSource.camera);
        },
        tooltip: 'Take a Photo',
        child: new Icon(Icons.camera_alt),
        heroTag: null,
      ),

      new FloatingActionButton(
          onPressed: () {
            getImage(ImageSource.gallery);
          },
          tooltip: 'Pick Image from gallery',
          child: new Icon(Icons.photo_library),
          heroTag: null,
      ),

2 个答案:

答案 0 :(得分:1)

列出文件的功能出现问题 我认为你应该使用这个函数获取子文件夹中的所有文件。

public List<File> listFiles(String dirPath) {
    List<File> files = new ArrayList<>();
    File dir = new File(dirPath);

    if(dir.isDirectory()) {
        for(File file : dir.listFiles()) {
            if(file.isDirectory()) files.addAll(listFiles(file));
            else files.add(file);
        }
    }

    return files;
}

如您所见,此函数以递归方式列出文件。

答案 1 :(得分:0)

iRandomXx的答案是正确的,这是一个递归问题。如果它对你有用,我想加入它。

考虑将逻辑分开一点。

1-使用递归方法获取所有文件以进行处理。看起来你只对文件(而不是目录)感兴趣。 iRandomXx的方法只获取文件并离开目录,使if-directory检查冗余(我将其删除)。

2-迭代列表并对每个文件执行任何操作。如果发生异常,您应该对其执行一些有用的操作,例如向用户显示有意义的错误消息或将其添加到错误列表中。

btnBasla.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // get all files first
        File files[]=listFiles(Path2.toString()); // iRandomX's recursive method
        for (File f : files) {
            // your validation check for extensions
            // modified a bit
            try {
                String fName = f.getName();
                int dotPos = fName.lastIndexOf('.');
                if(dotPos > 0) {
                    String extension = fName.substring(dotPos);
                    if(VALID_EXTENSIONS.contains(extension)) {
                        textField.append(islem.koddegıstır(f.getAbsolutePath())+"\n");
                    }
                }
            } catch (Exception e) {
                // do something useful with the exception, like show the user an error dialog
            }
        }
    }
}


// private class member
private static final List<String> VALID_EXTENSIONS = new ArrayList<>();

// static block to initialize valid extensions
static {
    VALID_EXTENSIONS.add(".txt");
    VALID_EXTENSIONS.add(".sub");
    VALID_EXTENSIONS.add(".srt");
}

// iRandomX's recursive method here