Home Java Example Java Io Java FileInputStream Example

Related Tutorials


 
 

Share on Google+Share on Google+

Java FileInputStream Example

Advertisement
I this page we have given a tutorial on Java FileInputStream. Learn Java FileInputStream with the help of an Example code.

Reading a file using FileInputStream

     

Reading a file using FileInputStream

Java has Two types of streams- Byte & Characters. For reading and writing binary data, byte stream is incorporated. The InputStream abstract class is used to read data from a file. The FileInputStream is the subclass of the InputStream abstract class. The FileInputStream  is used to read data from a file.

The read() method of an InputStream returns an int which contains the byte value of the byte read. If there is no more data left in stream to read, the read() method returns -1 and it can be closed after this. One thing to note here, the value -1 is an int not a byte value.

Given below example will give you a clear idea :

Example :

The content in the Devfile.txt :


The text shown here will write to a file after run

FileInStreamDemo.java

import java.io.*;

public class FileInStreamDemo {

public static void main(String[] args) {

// create file object
File file = new File("DevFile.txt");

int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;

try {
fin = new FileInputStream(file);

while ((ch = fin.read()) != -1)
strContent.append((char) ch);

fin.close();

} catch (FileNotFoundException e) {
System.out.println("File " + file.getAbsolutePath()
+ " could not be found on filesystem");
} catch (IOException ioe) {
System.out.println("Exception while reading the file" + ioe);
}

System.out.println("File contents :");
System.out.println(strContent);

}
}

Output :

The command prompt will show you the following data :

File contents :    
The text shown here will write to a file after run 

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 19, 2011

Related Tutorials

Discuss: Java FileInputStream Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
yusuf
April 10, 2012
not so gud

itz not that promising ..niid much exposure @ this level.
DMCA.com