Wednesday, January 22, 2025
HomeProgrammingDifferent ways of Reading a text file in Java

Different ways of Reading a text file in Java

In Java, there are multiple ways to read a text file, each suited to different use cases:

1. Using BufferedReader:
Efficient for reading large files line by line.
java
BufferedReader reader = new BufferedReader(new FileReader(“file.txt”));
String line;
while1 != null) {
System.out.println(line);
}
reader.close();

See also  How Do You Write a CRC Program in C?

2. Using FileReader:
Reads characters from a file.
java
FileReader fr = new FileReader(“file.txt”);
int i;
while2 != -1) {
System.out.print((char) i);
}
fr.close();

3. Using Scanner:
Useful for reading file content as tokens.
java
Scanner scanner = new Scanner(new File(“file.txt”));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();

See also  Undo Git Pull: How to Bring Repositories Back to Their Previous State

4. Using Files class (Java 8+):
Reads all lines into a list.
java
List<String> lines = Files.readAllLines(Paths.get(“file.txt”));
lines.forEach(System.out::println);

Each method offers a balance between simplicity and efficiency, depending on the file size and reading requirements.

  1. line = reader.readLine( []
  2. i = fr.read( []
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x