Java: Read a file line by line and store it into a variable
Java Input-Output: Exercise-13 with Solution
Write a Java program to read a file line by line and store it in a variable.
Sample Solution:
Java Code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
public class exercise13 {
public static void main(String a[]){
StringBuilder sb = new StringBuilder();
String strLine = "";
String str_data = "";
try {
BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
while (strLine != null)
{
if (strLine == null)
break;
str_data += strLine;
strLine = br.readLine();
}
System.out.println(str_data);
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}
Sample Output:
Welcome to w3resource.com.Append this text.Append this text.Append this text.Append this text.Append this text .Append this text.Append this text.
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to read a plain text file.
Next: Write a Java program to store text file content line by line into an array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/io/java-io-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics