How to Read a File Line by Line and Store It into a Variable in Java


In this example we will show a buffer stream reading method which can be read line by line.

Source Code

package com.beginner.examples;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileContentsVariables {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		
		try{
		//Create buffer character stream read	
		BufferedReader buffStream=
				new BufferedReader(new FileReader("Test.txt"));
		
		StringBuilder sBuilder = new StringBuilder();
		String lin e= null;
		
		//Reading a row is added to the StringBuilder
		while((line = buffStream.readLine())! = null)
		{
			sBuilder.append(line+"rn");
		}
		
		String contentString = sBuilder.toString();
		
		
		System.out.println(contentString);
		}
		catch (IOException e) {
			e.printStackTrace();
			
		}

	}

}

Output:

I like Java

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments