How do i open a file in java?


Ad

Advertisements

Joined
Mar 3, 2021
Messages
243
Reaction score
29
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.
 
Joined
Mar 3, 2021
Messages
243
Reaction score
29
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);
}
 
Joined
Jan 24, 2022
Messages
30
Reaction score
1
The open() method of the Desktop is used to open a file in Java. It takes a file as an argument. The method is:

public void open (File file) throws IOException
 
Joined
Mar 28, 2022
Messages
48
Reaction score
6
Here's a working load function example from my Loot Table class, that loads data in from a CSV file:

Java:
 /**
   * Load a set of loot items into loot table from a Comma Separated Value (CSV) file
   * @param fileName expected CSV format: | String name | int tries |
   * @throws NumberFormatException if 2nd column isn't an integer (extra space?)
   * @throws FileNotFoundException if can't find the CSV file (path & extension?)
   * @throws IOException other I/O & storage problems
   */
  public void load(String fileName){
    try {
      BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
      String lineItem;

      while ((lineItem = fileReader.readLine()) != null) {
        String[] lootDetails = lineItem.split(",");

        lootRecord record = new lootRecord();
        record.name       = lootDetails[0];
        record.tries      = Integer.valueOf(lootDetails[1]);
        record.dropChance = calcDropChance(record.tries);

        table.add(record);
      }
      fileReader.close();
    }
    catch (NumberFormatException e) {
      System.out.println("Invalid String: Integer count of tries expected");
      e.printStackTrace();
    }
    catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  } // load
 
Ad

Advertisements

Joined
Jan 24, 2022
Messages
30
Reaction score
1
I have gone through some more options to open a Java file. You can have a look and decide :
1. Java Desktop class
2. Java FileInputStream class
3. Java BufferedReader class
4. Java FileReader class
5. Java Scanner class
6. Java NIO package
 

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