Read from a file and assign to array [] [] in Java [closed]


How to read a txt file with an 8x11 matrix that has several char and put it in char [][] ?

The txt can have this form:


How do you read the previous txt from Java and put it as is with its rows and columns in char [][] ? Not in a vector [] , but in a matrix, respecting the rows and columns.

asked by Keka Bron 03.12.2016 в 18:59

1 answer


I would be using the BufferedReader class

Gets the instance to be able to read the file

 public BufferedReader getBuffered(String link){

    FileReader lector  = null;
    BufferedReader br = null;
    try {
         File Arch=new File(link);
           System.out.println("No existe el archivo");
           lector = new FileReader(link);
           br = new BufferedReader(lector);
    } catch (Exception e) {
    return br;

We read the file line by line and save it in the character array

 public void readTxt(){
    try {
        //ruta de tu archivo
        String ruta = "archivo.txt"
        BufferedReader br = getBuffered(ruta);
        //leemos la primera linea
        String linea =  br.readLine();
        //creamos la matriz vacia
        char[][] = new char[8][11];
        int contador = 0;
        while(linea != null){
            String[] values = linea.split(",");
            //recorremos el arrar de string
            for (int i = 0; i<values.length; i++) {
                //se obtiene el primer caracter de el arreglo de strings
                char[contador][i] = values[i].charAt(0);
            linea = br.readLine();
    } catch (IOException | NumberFormatException e) {
answered by 03.12.2016 / 19:34