Pass a txt to an array in JAVA

0

I need help. I have the following information in a text file .txt

Isabel Garcia,10,10,10,10,10,10,10  
Luis Fernando,10,09,09,09,09,09,09  
Isabel Flores,10,09,09,09,09,09,09

What would be the code to read the txt that is saved in a certain route and convert it to a two-dimensional array in JAVA?

So far I only have this code with WHILE but it does not save it in an array, it just reads it and shows it:

File calificaciones; 
FileReader leerArchivo;
leerArchivo = new FileReader("c:/calificaciones.txt"); 
BufferedReader textoArchivo = new BufferedReader(leerArchivo); 
while (cadena!=null) {
    cadena= textoArchivo.readLine();
    if (cadena!=null) {
        System.out.println(cadena);
   }
}
textoArchivo.close();
leerArchivo.close();

I need the code to save the name in one position, for example [0] [0], the first qualification in [0] [1] and so on. Separate the data by ",".

Can anyone help me?

    
asked by Alberto 20.11.2018 в 23:06
source

4 answers

0

I find that using a list of support and the split method can manipulate the file information the way you need it.

ArrayList<String[]> AUX = new ArrayList<>();
int lineas = 0;//Para numero de filas de la matriz
int cols = 0;//Para numero de columnas de la matriz

File calificaciones; 
FileReader leerArchivo;
leerArchivo = new FileReader("c:/calificaciones.txt"); 
BufferedReader textoArchivo = new BufferedReader(leerArchivo);

//Quiza no sea la manera mas optima de hacer la lectura del archivo... 
while (cadena!=null) {
  cadena= textoArchivo.readLine();
  if (cadena!=null) {
    //System.out.println(cadena);
    AUX.add(cadena.split(","));//Almacena cada array (lineas del archivo) en la lista
    lineas++;
  }
}

if(AUX.size()>0) {
  System.out.printf("Archivo a Matriz:%n");
  cols = AUX.get(0).length;
  info = new String[lineas][cols];

  for(int i=0; i<lineas; i++) {
    for(int j=0; j<cols; j++) {
      //Captura el elemento (array) de la lista y [j] trae el dato en esa posición del arreglo.
      info[i][j] = AUX.get(i)[j];
      System.out.print(info[i][j]+"\t");
    }
    System.out.println();
  }
} else {
  System.printf("No hay datos%n");
}

textoArchivo.close();
leerArchivo.close();

In this way, the matrix with the data is duly tabulated.

    
answered by 21.11.2018 / 02:03
source
1

This I think helps you.

Create a txt on your PC with the address that appears inside the code or wherever you like. But keep in mind that you must modify that address in java.

public static void main(String[] args) {

    File archivo = null;
    FileReader Fr = null;
    BufferedReader br = null;
    try {
        archivo = new File("C:/TIENDA/MATRIZ.txt"); // Ruta desde donde se lee el txt
        Fr = new FileReader(archivo.toString());
        br = new BufferedReader(Fr);
        String linea;
        String delimiter = ","; //Separador dentro del txt. Cuando crees tu archivo de texto en la maquina separa los números por comas. No los pongas en linea recta, pon uno sobre otro

        String matriz[][] = new String[2][2]; // Te leera una matriz de 2*2

        int numlinea=0;

        while (((linea = br.readLine()) != null)) {

            String a[]=linea.split(delimiter);

            for (int l = 0; l < a.length; l++) {
                matriz[numlinea][l] = a[l];
            }
            numlinea++;
        }
         System.out.println("MATRIZ");
         System.out.println("------");
           for (int filas = 0; filas < matriz.length; filas++) {
                for (int colum = 0; colum < matriz[filas].length; colum++) {
                    System.out.print(matriz[filas][colum]+" ");
                }
                System.out.println();   
            }
    } catch (IOException e) {
        System.out.println(e);
    }
}
    
answered by 21.01.2019 в 23:25
0
package arrays;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GuardarArray {

    public static void main(String[] args) {
        runTest();
    }

    public static void runTest() {
        String filePath = "c:/calificaciones.txt";
        FileReader leerArchivo;
        BufferedReader textoArchivo;
        List content;
        try {
            leerArchivo  = new FileReader(new File(filePath));
            textoArchivo = new BufferedReader(leerArchivo);

            content = getContent(textoArchivo);
            try {
                textoArchivo.close();
                leerArchivo.close();
            } catch (IOException ex) {
                System.err.println("Error -> " + ex);
            }

            // Show the results
            if (content != null) {
                showResults(content);
            }

        } catch (FileNotFoundException ex) {
            System.err.println("Error -> " + ex);
        }
    }

    private static List getContent(BufferedReader bufReader) {
        List content = new ArrayList();
        String lineContent = "";
        int lineNumber     = 0;
        while (lineContent != null) {

            try {
                lineContent = bufReader.readLine();
            } catch (IOException ex) {
                System.err.println(
                   "Error reading line: " + lineNumber + " -> " + ex);
            }
            if (lineContent != null && ! lineContent.equals("")) {
                System.out.println("Line readed: " + lineContent);

                String[] lineElements = lineContent.split(",");
                content.add(lineElements);
            }

            lineNumber++;
        }

        return content;
    }

    private static void showResults(List content) {
        System.out.println("Readed contents .................................");

        for(int i = 0; i < content.size(); i++) {
            String[] lineElements = (String[]) content.get(i);
            for (String lineElement : lineElements) {
                System.out.print(lineElement + " ");
            }
            System.out.println();
        }
    }
}

I have saved the result in a list from the getContent() method that the instance of BufferedReader passed to. In the example I show its content with the method: showResults() .

Once you can read the file row by row, since they have a certain format (data separated by commas), you can obtain an array of strings with the data of each row, obtaining their elements from the separator (, ):

String[] lineElements = lineContent.split(",");

As in theory it is not known what number of rows the file has, it saves each one of the arrays that are obtained previously in a list:

content.add(lineElements);

The list will be returned at the end of the reading of the file.

    
answered by 21.11.2018 в 00:18
0

The first algorithm is to read plain text files at the location of your local disk

public Stream<String> leerAchivoLocal(String ruta) {
    Stream<String> lineas = null;

    try {
        lineas = Files.lines(Paths.get(ruta), Charset.forName("UTF-8"));

    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(ArchivoImpl.class.getName()).log(Level.SEVERE, null, ex);
    }finally{
       if(lineas != null) lineas.close();
    }

    return lineas;
}

The second algorithm, once you have read the whole document, you can do the conversion

public String[][] texto2arreglo(Stream<String> archivo){
    List<String> textos = archivo.collect(Collectors.toList());

    int filas = textos.size();
    int columnas = textos.get(0).split(",").length;

    String arreglo[][] = new String[filas][columnas];

    IntStream.range(0, filas).forEach(y -> {
        String linea = textos.get(y);
        IntStream.range(0, columnas).forEach(x -> {
            arreglo[y][x] = linea.split(",")[x];
        });
    });

   return arreglo;
}
    
answered by 21.11.2018 в 01:55