En este ejemplo, aprenderemos a cargar un archivo como flujo de entrada usando la clase FileInputStream en Java.
Para comprender este ejemplo, debe tener el conocimiento de los siguientes temas de programación de Java:
- Clase de archivo Java
- Clase InputStream de Java
- Clase Java FileInputStream
Ejemplo 1: Programa Java para cargar un archivo de texto como InputStream
import java.io.InputStream; import java.io.FileInputStream; public class Main ( public static void main(String args()) ( try ( // file input.txt is loaded as input stream // input.txt file contains: // This is a content of the file input.txt InputStream input = new FileInputStream("input.txt"); System.out.println("Data in the file: "); // Reads the first byte int i = input.read(); while(i != -1) ( System.out.print((char)i); // Reads next byte from the file i = input.read(); ) input.close(); ) catch(Exception e) ( e.getStackTrace(); ) ) )
Salida
Datos en el archivo: este es un contenido del archivo input.txt.
En el ejemplo anterior, tenemos un archivo llamado input.txt . El contenido del archivo es
This is a content of the file input.txt.
Aquí, usamos la FileInputStream
clase para cargar el archivo input.txt como flujo de entrada. Luego usamos el read()
método para leer todos los datos del archivo.
Ejemplo 2: Programa Java para cargar un archivo Java como InputStream
Considere que tenemos un archivo Java llamado Test.java ,
class Test ( public static void main(String() args) ( System.out.println("This is Java File"); ) )
También podemos cargar este archivo Java como flujo de entrada.
import java.io.InputStream; import java.io.FileInputStream; public class Main ( public static void main(String args()) ( try ( // file Test.java is loaded as input stream InputStream input = new FileInputStream("Time.java"); System.out.println("Data in the file: "); // Reads the first byte int i = input.read(); while(i != -1) ( System.out.print((char)i); // Reads next byte from the file i = input.read(); ) input.close(); ) catch(Exception e) ( e.getStackTrace(); ) ) )
Salida
Datos en el archivo: class Test (public static void main (String () args) (System.out.println ("This is Java File");))
En el ejemplo anterior, hemos utilizado la FileInputStream
clase para cargar el archivo Java como flujo de entrada.