How do i open a file in java?


Ad

Advertisements

Joined
Mar 3, 2021
Messages
174
Reaction score
19
Assuming it's a text file, check out the BufferedReader class. Right at the top of it's API page it's got BufferedReader in = new BufferedReader(new FileReader("foo.in"));. Then, you use read() or readLine() to start pulling text out of it. Check each function's doc on how to detect the end of the file.
 
Ad

Advertisements

Joined
Mar 3, 2021
Messages
174
Reaction score
19
The common idiom you'll see is this. Note that this isn't catching exceptions that can be thrown, e.g., if the file doesn't exist or you lack permissions to read it.

Java:
BufferedReader in = new BufferedReader(new FileReader("foo.in"));.
String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top