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

1

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:

%,%,%,%,%,%,%,%,%,%,%
%,%,%,h,o,l,a,%,%,%,%
%,%,%,%,%,%,%,%,%,%,%
%,%,%,m,u,n,d,o,%,%,%
%,%,%,%,%,%,%,%,%,%,%
%,%,%,%,%,%,%,%,%,%,%
%,%,%,%,%,%,%,%,%,%,%

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
source

1 answer

2

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);
        if(!Arch.exists()){
           System.out.println("No existe el archivo");
        }else{
           lector = new FileReader(link);
           br = new BufferedReader(lector);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    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];
        //contador
        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);
            }
            contador++;
            linea = br.readLine();
        }
    } catch (IOException | NumberFormatException e) {
        e.printStackTrace();
    }
}
    
answered by 03.12.2016 / 19:34
source