Java-programma om bestand te laden als InputStream

In dit voorbeeld zullen we leren om een ​​bestand te laden als een invoerstroom met behulp van de FileInputStream-klasse in Java.

Om dit voorbeeld te begrijpen, moet u kennis hebben van de volgende Java-programmeeronderwerpen:

  • Java-bestandsklasse
  • Java InputStream-klasse
  • Java FileInputStream-klasse

Voorbeeld 1: Java-programma om een ​​tekstbestand te laden als 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(); ) ) )

Uitvoer

 Gegevens in het bestand: Dit is een inhoud van het bestand input.txt.

In het bovenstaande voorbeeld hebben we een bestand met de naam input.txt . De inhoud van het bestand is

 This is a content of the file input.txt.

Hier hebben we de FileInputStreamklasse gebruikt om het bestand input.txt als invoerstroom te laden . Vervolgens hebben we de read()methode gebruikt om alle gegevens uit het bestand te lezen.

Voorbeeld 2: Java-programma om Java-bestand te laden als InputStream

Stel dat we een Java-bestand hebben met de naam Test.java ,

 class Test ( public static void main(String() args) ( System.out.println("This is Java File"); ) )

We kunnen dit Java-bestand ook laden als invoerstroom.

 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(); ) ) )

Uitvoer

 Gegevens in het bestand: class Test (public static void main (String () args) (System.out.println ("Dit is Java-bestand");))

In het bovenstaande voorbeeld hebben we de FileInputStreamklasse gebruikt om het Java-bestand als een invoerstroom te laden.

Interessante artikelen...