English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

¿Es posible leer hasta el final de DataInputStream en Java sin capturar EOFException?

En algunos casos, al leer el contenido del archivo, en este caso se alcanza el final del archivo, se lanza EOFException.

Especialmente, se lanza esta excepción cuando se lee datos utilizando objetos de flujo de entrada. En otros casos, se lanza un valor específico cuando se alcanza el final del archivo.

En la clase DataInputStream, se proporcionan varios métodos, comoreadboolean(),readByte(),readChar()Etc. Valores originales leídos. Cuando se utilizan estos métodos para leer datos desde el archivo, se lanza EOFException cuando se alcanza el final del archivo.

Ejemplo

El siguiente programa muestra cómo manejar EOFException en Java.

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String[] args) throws Exception {
      //Leer datos del usuario
      Scanner sc = new Scanner(System.in);
      System.out.println("Ingrese una cadena: ");
      String data = sc.nextLine();
      byte[] buf = data.getBytes();
      //Escribir en el archivo
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt"));
      for (byte b : buf) {
         dos.writeChar(b);
      }
      dos.flush();
      //Leyendo del archivo creado anteriormente utilizando el método readChar()
      DataInputStream dis = new DataInputStream(new FileInputStream("D:\\data.txt"));
      while(true) {
         char ch;
         ch = dis.readChar();
         System.out.print(ch);
      }
   }
}

Resultado de salida

Ingrese una cadena:
hello how are you
helException en hilo "main" lo how are youjava.io.EOFException
   at java.io.DataInputStream.readChar(Unknown Source)
   at MyPackage.AIOBSample.main(AIOBSample.java:27)

lectura de DataInputStream sin capturar la excepción

No se puede usarDataInputStreamLa clase lee el contenido del archivo hasta que no llega al final del archivo. Si es necesario, se pueden usar otros subclases de la interfaz InputStream.

Ejemplo

En el siguiente ejemplo, utilizamos la clase FileInputStream en lugar de DataInputStream para rewritten el programa anterior, para leer datos desde el archivo.

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String[] args) throws Exception {
      //Leer datos del usuario
      Scanner sc = new Scanner(System.in);
      System.out.println("Ingrese una cadena: ");
      String data = sc.nextLine();
      byte[] buf = data.getBytes();
      //Escribir en el archivo
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt"));
      for (byte b : buf) {
         dos.writeChar(b);
      }
      dos.flush();
      //Leyendo del archivo creado anteriormente utilizando el método readChar()
      File file = new File("D:\\data.txt");
      FileInputStream fis = new FileInputStream(file);
      byte b[] = new byte[(int) file.length()];
      fis.read(b);
      System.out.println("Contenido del archivo: ");+new String(b));
   }
}

Resultado de salida

Ingrese una cadena:
Hello how are you
Contenido del archivo: H e l l o h o w a r e y o u
Te gustará