Articles Directory

  • 0

How to read file in Java Using FileInputStream

After you tried to write files using FileOutputStream, then you need to read that files and now we will study How to read file in Java Using FileInputStream. 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.

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();
			}
		}
	}
}

Here is an updated JDK7 How to read file in Java Using FileInputStream example, using new “try resource close” method to handle file easily.

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();
		}
	}
}

 

loading...

Related posts

Related posts