In Java, FileInputStream is a bytes stream class that’s used to read bytes from file. The following example will use FileInputStream to read a file named “c:/robots.txt” and display its content to console.

//This is content of file : c:/robots.txt
User-agent: *
Disallow: /wp-admin/
Disallow: /wp-includes/
Disallow: /wp-includes-test/

See below full example.

package com.mkyong.io;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class ReadFileExample {
 
	public static void main(String[] args) {
 
		File file = new File("C:/robots.txt");
		FileInputStream fis = null;
 
		try {
			fis = new FileInputStream(file);
 
			System.out.println("Total file size to read (in bytes) : "
					+ fis.available());
 
			int content;
			while ((content = fis.read()) != -1) {
				// convert to char and display it
				System.out.print((char) content);
			}
 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}

Following result will be displayed on console.

Total file size to read (in bytes) : 90
User-agent: *
Disallow: /wp-admin/
Disallow: /wp-includes/
Disallow: /wp-includes-test/

JDK 7 example

An updated JDK7 example, using new “try resource close” method to handle file easily.

package com.mkyong.io;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class ReadFileExample {
 
	public static void main(String[] args) {
 
		File file = new File("C:/robots.txt");
 
		try (FileInputStream fis = new FileInputStream(file)) {
 
			System.out.println("Total file size to read (in bytes) : "+ fis.available());
 
			int content;
			while ((content = fis.read()) != -1) {
				// convert to char and display it
				System.out.print((char) content);
			}
 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

References

  1. http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
  2. http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/
Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts