Reading the contents of a folder and converting a text file to an array

I am trying to upload files to my sorting algorithm program. These are the folder instructions:

folders:

512   1024   2048   4096   8192   16384 ...

Files in each folder:

1.txt   2.txt ...

Content in each file:

321
66
188
134
...

I was able to read all the text files in each folder. Instead of reading each folder contents manually, how can I read them all in one go?

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

+4
source share
2 answers

You are already using the File class to read files from a directory. You just need to go one level deeper. It might look something like this:

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);
   }
}
+3
source

, Google Guava TreeTraverser . Iterable:

for(File file : Files.fileTreeTraverser()
                         .preOrderTraversal(new File("/root/folder"))){
    // handle each file and folder in the tree here
}

, .

0

Source: https://habr.com/ru/post/1612464/


All Articles