Java program demonstrating the usage of FileInputStream in java.io package-Different Way

The FileInputStream class creates an InputStream that you can use to read bytes from a file.

For this you need to create a text file called Hello.txt with some text. We will read from this file and display it in console.

//Java Program demonstrating the FileInputStream Class in java.io package

FileInputStreamDemo1.java

Check out the while loop used for looping the File

import java.io.*;

class FileInputStreamDemo1
{
	public static void main(String[] args)
	{
		try{
			File f = new File("Hello.txt");
			int size;
			FileInputStream fis = new FileInputStream(f);
			System.out.println("Total Available Bytes: " + (size = fis.available()));

			int i = 0;
			while(i!=-1)
			{
				i = fis.read();
				if(i!=-1)
				System.out.print((char)i);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

Snapshot of the o/p- Same as this program

https://programmingpalace.wordpress.com/2011/08/27/java-program-demonstrating-the-usage-of-fileinputstream-in-java-io-package/         

Advertisements

Java program demonstrating the usage of FileInputStream in java.io package

The FileInputStream class creates an InputStream that you can use to read bytes from a file.
Here we will be reading from a file called Hello.txt

It contains the following text

===

Hello World from Java.

Java is a high level programming language used throughout the
world.

Java is platform independent with a rich API.

Hope you will enjoy being a part of Java.

===

Create Text File Hello.txt  and keep it in the same directory as your program

//Java Program demonstrating the FileInputStream Class in java.io package

FileInputStreamDemo.java


import java.io.*;

class FileInputStreamDemo
{
	public static void main(String[] args)
	{
		try{
			File f = new File("Hello.txt");
			int size;
			FileInputStream fis = new FileInputStream(f);

			System.out.println("Total Available Bytes: " + (size = fis.available()));
			int n = size = fis.available();

			int i = 0;

			for(i=0; i<n;i++)
			{
				System.out.print((char)fis.read());
			}
		}//try
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

Snapshot of the o/p

When we run the program, the contents of the file are displayed on the console.