读取文件夹内容并将文本文件转换为数组

Read folder content and convert the text file into array

我正在尝试将文件加载到我的排序算法程序中。 这是文件夹说明:

文件夹:

512   1024   2048   4096   8192   16384 ...

每个文件夹中的文件:

1.txt   2.txt ...

各文件内容:

321
66
188
134
...

我设法读取了每个文件夹中的所有文本文件。不用手动读取每个文件夹的内容,如何一次性读取它们?

void setup() {
    String url = sketchPath("numbers/512/");
    String[] stringData = null;
    int[] intData = null;

    runTest(stringData, intData, url);
}

void runTest(String[] text, int[] number, String url) {

    File directory = new File(url);
    File[] listOfFiles = directory.listFiles();
    for (File file : listOfFiles) {
        //println(file.getName());
        text = loadStrings(file);
        number = int(text);
        sortInteger(number);
    }
}

int[] sortInteger(int[] input) {

    int temp;

    for (int i = 1; i < input.length; i++) {
        for (int j = i; j > 0; j--) {
            if (input[j] < input[j - 1]) {
                temp = input[j];
                input[j] = input[j - 1];
                input[j - 1] = temp;
            }
        }
    }
    println(input);
    return input;
}

您已经在使用 File class 从目录中读取文件。你只需要更深入一层。它可能看起来像这样:

for(File directory : new File("numbers").listFiles()){
   File[] listOfFiles = directory.listFiles();
   for (File file : listOfFiles) {
        //println(file.getName());
        text = loadStrings(file);
        number = int(text);
        sortInteger(number);
   }
}

如果您可以使用实用程序库,我会推荐 Google Guava's TreeTraverser class 来完成这项工作。这允许您通过单个 Iterable:

遍历文件树中的文件和文件夹
for(File file : Files.fileTreeTraverser()
                         .preOrderTraversal(new File("/root/folder"))){
    // handle each file and folder in the tree here
}

除了预序tree traversal之外,class还提供了以post序和广度优先顺序迭代树的方法。