English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to load a file as an input stream using the FileInputStream class in Java.
To understand this example, you should be familiar with the followingJava programmingTopic:
import java.io.InputStream; import java.io.FileInputStream; public class Main { public static void main(String args[]) { try { //The file input.txt is loaded as an input stream // Content of input.txt file: //This is the 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 the content of the file input.txt.
In the above example, we have a file namedinput.txtThe content of the file is
This is the content of the file input.txt.
Here, we use the FileInputStream class to loadinput.txtLoad the file as an input stream and then use the read() method to read all the data from the file.
Suppose we have a file namedTest.javaJava file,
class Test { public static void main(String[] args) { System.out.println("This is Java File"); } }
We can also load this Java file as an input stream.
import java.io.InputStream; import java.io.FileInputStream; public class Main { public static void main(String args[]) { try { // Load the file Test.java as an input stream 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.