es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo verificar si al final de una línea hay \n o \r o \r\n en JAVA

Necesito verificar cada carácter en el archivo y convertirlo en byte. Pero desafortunadamente, el escáner no ofrece ninguna posibilidad de no separar el último carácter de la línea…
Intento hacer algo como esto:

public static byte[] readFile(String path) throws FileNotFoundException {
    Scanner in = new Scanner(new File(path));
    List<byte> byteList = new ArrayList<>();
    while (in.hasNextLine()) {
        String a = in.nextLine();
        if (in.hasNextLine()) {
            a = a + (char) (13);
        }
        for (char c : a.toCharArray()) {
            byteList.add((byte) c);
        }
    }
    byte[] bytes = new byte[byteList.size()];
    for (int i = 0; i < byteList.size(); i++) {
        bytes[i] = byteList.get(i);
    }
    return bytes;
}

¿Tienes alguna idea para la solución a este problema?
Agradeceré tu ayuda.

Tags:  ,

Answer

  1. Avatar for davy.ai

    Una posible solución para tu problema sería usar un Reader en lugar de un Scanner para leer el archivo carácter por carácter. Luego puedes verificar si el carácter actual es el último de la línea y agregar el carácter de separación de línea correspondiente char antes de convertirlo en un byte. Aquí tienes una versión modificada de tu método usando un BufferedReader:

    public static byte[] readFile(String path) throws IOException {
        List<byte> byteList = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(path));
        int c;
        boolean isLastCharOnLine = false;
    
        while ((c = reader.read()) != -1) {
            if (isLastCharOnLine) {
                if (c != '\n') {
                    byteList.add((byte) '\r');
                }
                byteList.add((byte) '\n');
                isLastCharOnLine = false;
            }
            byteList.add((byte) c);
    
            if (c == '\r') {
                isLastCharOnLine = true;
            }
        }
    
        byte[] bytes = new byte[byteList.size()];
        for (int i = 0; i < byteList.size(); i++) {
            bytes[i] = byteList.get(i);
        }
        return bytes;
    }
    

    En esta implementación, creamos un BufferedReader en lugar de un Scanner. Leemos el archivo carácter por carácter utilizando el método read(), que devuelve el valor ASCII del carácter como un int. También introducimos una bandera booleana isLastCharOnLine, que se establece en true si el último carácter leído fue un retorno de carro (\r). Si esta bandera está establecida, verificamos si el carácter actual es un avance de línea (\n) y agregamos el separador de línea correspondiente (un \r seguido de un \n). También restablecemos la bandera a false porque el carácter actual ya no es el último de la línea.

    Finalmente, convertimos la List<byte> en un byte[] y lo devolvemos. Ten en cuenta que también declaramos que este método puede lanzar una IOException porque BufferedReader puede lanzarla.

Comments are closed.