Read a text file and compare its contents with an arraylist in java

0

My questions is as follows, how can I compare the content of a text file with the content of an arraylist? For example: I have a method that performs a search of files in a specified folder and lifts it in an arraylist, which would need to know how I could do to compare what is inside the array with what is inside the text file. In the txt file, I have stored the names of localities with the following structure: PDA01 - Buenos Aires

How do I know that within my array I have a file that starts with the PDA01 structure and indicate by msj that the file belongs to Buenos Aires ? / p>

I read the file.

public void leer(){
        try{
            // Abrimos el archivo con la ruta especificada.
            FileInputStream fstream = new FileInputStream(new File("Sucursales.txt"));
            // Creamos el objeto de entrada
            DataInputStream entrada = new DataInputStream(fstream);
            // Creamos el Buffer de Lectura
            BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
            String strLinea;
            // Leer el archivo linea por linea
            while ((strLinea = buffer.readLine()) != null)   {
                // Imprimimos la línea por pantalla
                System.out.println (strLinea);
            }
            // Cerramos el archivo
            entrada.close();
        }catch (Exception e){ //Catch de excepciones
            System.err.println("Ocurrio un error: " + e.getMessage());
        }
    }

File search

public void buscarArchivo(File ruta) {
//        Creo el vector que contendra todos los archivos de una ruta especificada.
        ArrayList<String> arrayArchivos = new ArrayList<>();
        File[] archivo = ruta.listFiles();
//        Evaluo si la carpeta especificada contiene archivos.
        if (archivo != null) {
//            Recorro el vector el cual tiene almacenado la ruta del archivo a buscar.
            for (int i = 0; i < archivo.length; i++) {
//                Evaluo si el archivo o la ruta es una carpeta.
                if (archivo[i].isDirectory()) {
//                    Le paso la nueva ruta de la carpeta si se cambia la ruta e busca nuevamente.
                    buscarArchivo(archivo[i]);
                } else {
//                    Evaluo el tipo de extencion. 
                    if (archivo[i].getName().endsWith(".pnd") || archivo[i].getName().endsWith(".ana") || archivo[i].getName().endsWith(".cnf")) {
                        contador++;
                        arrayArchivos.add(archivo[i].getName());
                        leerArchivos.leer();

                    }
                }
            }
            arrayArchivos.clear();
        }
    }

So far I have that, just list what I have inside the txt file, but I do not know how to make the comparison if within the arraylist there is a file with the structure PDA01 that belongs to BUENOS AIRES or PDA02 belongs to X province. I would greatly appreciate your help.

    
asked by Gerardo Ferreyra 27.08.2017 в 20:54
source

2 answers

0

I have managed to solve my problem in the following way.

I have my method read () which resivo as parametro a arraylist

    public void leer(ArrayList<String> arrayList) {
                    ArrayList<String> keyArray = new ArrayList<>();
                    Map<String, String> mapaCodigosArchivo = new HashMap();

                    try {
                        // Abrimos el archivo con la ruta especificada.
                        FileInputStream fstream = new FileInputStream(new File("Sucursales.txt"));
                        // Creamos el objeto de entrada
                        DataInputStream entrada = new DataInputStream(fstream);
                        // Creamos el Buffer de Lectura
                        BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
                        String contenido;
                        // Leer el archivo linea por linea
                        while ((contenido = buffer.readLine()) != null) {
    //                      Partimos el String.
                            String[] separador = contenido.split(",");
    //                      Agregamos al Map.
                            mapaCodigosArchivo.put(separador[0], separador[1]);
                        }
        //              Vaciamos el array en cada vuelta para que no sea un acumulador.
                        keyArray.clear();
                        //Recorremos el arrayList
                        for (String nombreArchivo : arrayList) {
                            String[] separador = nombreArchivo.split("_");
                            String codSucursal = separador[0].replace("PDA", "").trim();
//                          Agregamos al array temporal.
                            keyArray.add(codSucursal);
                        }
//                      Recorremos el map.
                        for (String key : mapaCodigosArchivo.keySet()) {
                            int encontrados = this.contarTicketPorSucursal(keyArray, key);
                            if (encontrados > 0) {
                                System.out.println("Tienes " + encontrados + " ticket pendiente de la sucursal: " + mapaCodigosArchivo.get(key));
                            }
                        }
                        // Cerramos el archivo
                        entrada.close();
                    } catch (Exception e) { //Catch de excepciones
                        System.err.println("Ocurrio un error: " + e.getMessage());
                    }
                }

We count the amount of files that exist in the same branch.

          private int contarTicketPorSucursal(ArrayList<String> keyArray, String key) {
            int contador = 0;
            for (int i = 0; i < keyArray.size(); i++) {
                if (keyArray.get(i).equals(key)) {
                    contador++;
                }
            }
            return contador;
        }

I hope someone will be of help.

    
answered by 17.09.2017 / 21:54
source
0

BuefferedReader has a method called lines () that returns a stream that you can browse and compare with the content of the arraylist.

BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));

buffer.lines().forEach() //java 8
    
answered by 29.08.2017 в 23:23