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

时间:2015-10-20 15:56:31

标签: java processing

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

文件夹:

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;
}

enter image description here enter image description here enter image description here

2 个答案:

答案 0 :(得分:3)

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

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);
   }
}

答案 1 :(得分:0)

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

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

除了预订tree traversal之外,该类还提供了按顺序和广度优先顺序迭代树的方法。

相关问题