Write a java program to Print File Content, Display File


First, a File object f_name is created to represent the file named "file.txt". Then, a FileInputStream object in_file is created to read from the file. The length() method of the File object is used to determine the length of the file in bytes, which is then stored in the len variable.

A byte array of length len is created using byte bytes[] = new byte[len]; . The read() method of the FileInputStream object is then used to read the contents of the file into the bytes array. The number of bytes read is returned by read(), which is then printed to the console using System.out.println("Size of File : " + in_file.read(bytes)); .

Finally, the contents of the file are converted to a String object using String f = new String(bytes); , and the String object is printed to the console using System.out.println("File Content is : " + f); . The close() method is used to close the FileInputStream object after reading the file.

Source Code

import java.io.*;
public class Display_File
{
	public static void main(String args[]) throws IOException
	{
		File f_name = new File("file.txt");
 
		FileInputStream in_file = new FileInputStream("file.txt");
		int len = (int) f_name.length();
 
		byte bytes[] = new byte[len];
 
		System.out.println("Size of File : " + in_file.read(bytes));
 
		String f = new String(bytes);
		System.out.println("File Content is : " + f);
 
		in_file.close();
	}
}

Output

Size of File : 21
File Content is : This is Java Programs