Home > Blockchain >  How to list folders and files from different paths stored in a json file - Java
How to list folders and files from different paths stored in a json file - Java

Time:02-27

I want to list all the folders and files from different paths stored in a json file in order to delete them later with a filter. In the folowing code I list the folders using the FILE class and only one path.

public class Depurador {
   public static void main(String[] args) {
   File ruta = new File("C:\\Users\\erick\\Desktop\\prueba");
   ImprimirFicheros1(ruta, 0);
}

public static void ImprimirFicheros1(File file, int nivelArbol){
   for(int i = 0; i < nivelArbol; i  ){
       System.out.print("-");
   }
   System.out.println(file.getName());
   
   if(file.isDirectory()){
       File[] listaFicheros = file.listFiles();
       for(File fichero : listaFicheros){
           ImprimirFicheros1(fichero, nivelArbol   2);
       }
   }
}

I would like to list all the folders and files from this json file and not only from one path.

{
    "Directorios":[
        {
            "ruta": "C:\\Users\\erick\\Desktop\\prueba",
            "periodo": 15,
            "archivos":["yyyy-mm-dd_reportesdetalles_1.csv, yyyy-mm-dd_reportesdetalles_2.csv"]
        },
        {
            "ruta": "C:\\Users\\erick\\Desktop\\test",
            "periodo": 20,
            "archivos":["yyyy-mm-dd_test_1.csv, yyyy-mm-dd_test_2.csv"]
        }
    ]
}

CodePudding user response:

You will need to deserialize the JSON string into object. You can use a library like jackson ObjectMapper

class Directory {

   private String ruta;
   private int periodo;
   private List<String> archivos;

   // getters and setters
}

or use a record (java 14 )

public record Directory(String ruta, int periodo, List<String> archivos) {}

public record Input(List<Directory> Directorios) {}

In your main function you can do this now.

// triple quote text block is java 13 
String jsonString = """
{
    "Directorios":[
        {
            "ruta": "C:\\Users\\erick\\Desktop\\prueba",
            "periodo": 15,
            "archivos":["yyyy-mm-dd_reportesdetalles_1.csv, yyyy-mm-dd_reportesdetalles_2.csv"]
        },
        {
            "ruta": "C:\\Users\\erick\\Desktop\\test",
            "periodo": 20,
            "archivos":["yyyy-mm-dd_test_1.csv, yyyy-mm-dd_test_2.csv"]
        }
    ]
}
""";
List<Directory> directories = new com.fasterxml.jackson.databind.ObjectMapper().readValue(jsonString, Input.class).getDirectorios();

for (Directory d : directories) {
   File ruta = new File(d.getRuta());
   ImprimirFicheros1(ruta, 0);
}
  • Related