Java Exercises: Read a plain text file
Java Input-Output: Exercise-12 with Solution
Write a Java program to read a plain text file.
Sample Solution:
Java Code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
public class Exercise12 {
public static void main(String a[]){
StringBuilder sb = new StringBuilder();
String strLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader("/home/students/test.txt"));
while (strLine != null)
{
sb.append(strLine);
sb.append(System.lineSeparator());
strLine = br.readLine();
System.out.println(strLine);
}
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. null
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to read a file content line by line.
Next: Write a java program to read a file line by line and store it into a variable.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework