Java: How to read a text file
To read a text file in Java, you can use the BufferedReader
class from the java.io
package. Here's an example of how to read a text file line by line in Java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String fileName = "path/to/file.txt";
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
while ((line = reader.readLine()) != null) {
// process the line
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, the BufferedReader
reads the text file line by line until the end of the file is reached. The readLine
method returns null
when the end of the file is reached.
You can also use the Files
class from the java.nio.file
package to read a text file in Java. Here's an example of how to use the Files
class to read a text file:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class Main {
public static void main(String[] args) {
String fileName = "path/to/file.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName));
for (String line : lines) {
// process the line
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, the readAllLines
method reads the entire text file and returns it as a List
of String
s, one for each line of the file.
I hope this helps! Let me know if you have any questions.