What is the correct code to read a text file in Java?
Question
What is the correct code to read a text file in Java?
Solution
Here is a simple example of how to read a text file in Java using the BufferedReader class:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("filename.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this code:
- We first import the necessary classes.
- We create a new BufferedReader object and pass a new FileReader object with the filename as a parameter.
- We read the first line using the
readLine()method and store the result in a variable. - We then enter a while loop that continues until
readLine()returns null, which means the end of the file has been reached. - Inside the loop, we print out the line read by the reader, and then read the next line.
- After the loop, we close the reader using the
close()method. - If an IOException occurs at any point, we catch it and print the stack trace.
Similar Questions
Which method is used to read a character from the FileReader class in Java?Question 3Answera.readChar()b.read()c.readLine()d.readString()
Which class in Java is used to read data line by line from a file?OptionsFileInputStreamBufferedReaderFileWriterOutputStream
Consider the codes below to read the content of a file. fr is a FileReader object.BufferedReader d=new BufferedReader(fr);String filecontent=d.readLine();Select one:TrueFalse
Which of these method of FileReader class is used to read characters from a file?Question 2Answera.read()b.scanf()c.get()d.getInteger()
the correct answerWhich of these class is used to read characters in a file?OptionsFileReaderFileInputStreamFileWriterInputStreamReader
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.