English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à charger un fichier en tant que flux d'entrée en utilisant la classe FileInputStream de Java.
Pour comprendre cet exemple, vous devriez comprendre les éléments suivantsProgrammation JavaSujet :
import java.io.InputStream; import java.io.FileInputStream; public class Main { public static void main(String args[]) { try { //Le fichier input.txt est chargé en tant que flux d'entrée // Le contenu du fichier input.txt est: //This is a content of the file input.txt. InputStream input = new FileInputStream("input.txt"); System.out.println("Data in the file: "); //Read the first byte int i = input.read(); while(i != -1) { System.out.print((char)i); //Read the next byte from the file i = input.read(); } input.close(); } catch(Exception e) { e.getStackTrace(); } } }
Output result
Data in the file: This is a content of the file input.txt.
Dans cet exemple, nous avons un fichier nomméinput.txtLe contenu du fichier est
This is a content of the file input.txt.
Ici, nous utilisons la classe FileInputStream pour chargerinput.txtCharger un fichier en tant que flux d'entrée. Ensuite, nous utilisons la méthode read() pour lire toutes les données du fichier.
Si nous avons un fichier nomméTest.javadu fichier Java,
class Test { public static void main(String[] args) { System.out.println("This is Java File"); } }
Nous pouvons également charger ce fichier Java en tant que flux d'entrée.
import java.io.InputStream; import java.io.FileInputStream; public class Main { public static void main(String args[]) { try { // Charger le fichier Test.java en tant que flux d'entrée InputStream input = new FileInputStream("Time.java"); System.out.println("Data in the file: "); // Read the first byte int i = input.read(); while(i != -1) { System.out.print((char)i); // Read the next byte from the file i = input.read(); } input.close(); } catch(Exception e) { e.getStackTrace(); } } }
Output result
Data in the file: class Test { public static void main(String[] args) { System.out.println("This is Java File"); } }
In the above example, we use the FileInputStream class to load the Java file as an input stream.