Write a java program to read a file line by line and store it into a variable


The code reads the content of a file named "file.txt" and stores it in a variable named "data". First, a BufferedReader object is created and is passed the file name "file.txt" to read the content of the file.

Then, a while loop is used to read each line of the file using the readLine() method of the BufferedReader object. If the line read is not null, its content is appended to the data string using the += operator. If the line read is null, it means the end of the file has been reached, so the while loop is terminated using a break statement.

Finally, the data variable is printed to the console using the println() method of the System.out object. If the file is not found or there is an error while reading the file, an exception is caught and an error message is printed to the console.

Source Code

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader; 
public class StoreVariable
{ 
	public static void main(String a[])
	{
		String line = "";
		String data = "";
		try 
		{
			BufferedReader buf = new BufferedReader(new FileReader("file.txt"));
			while (line != null)
			{
				if (line == null)
				{
					break;
				}
				data += line;
				line = buf.readLine();                
			}
			System.out.println(data);
			buf.close();
		}
		catch (FileNotFoundException e)
		{
			System.err.println("File Not Found");
		}
		catch (IOException io)
		{
			System.err.println("Unable to Read the File");
		}
	}
}

Output

Python Exercises