Using java.io library in eclipse so FileInputStream can read a dat file

后端 未结 2 1076
南旧
南旧 2020-12-02 02:41
  • Goal: Print the data from a .dat file to the console using Eclipse.
    • (Long-Term Goal): Executable that I can pass a .dat fil
2条回答
  •  攒了一身酷
    2020-12-02 03:04

    I would strongly recommend spending some time reading through the Java Trails Tutorials. To answer your specific question, look at Lesson: Exceptions.

    To oversimplify, just wrap the file-handling code in a try...catch block. By example:

    package frp;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    
    public class FileRead {
    
        public static void main(String[] args) {
            try {
                FileReader file = new FileReader(new File("dichromatic.dat"));
                BufferedReader br = new BufferedReader(file);
                String temp = br.readLine();
                while (temp != null) {
                    temp = br.readLine();
                    System.out.println(temp);
                }
                file.close();
            } catch (FileNotFoundException fnfe) {
                System.err.println("File not found: " + fnfe.getMessage() );
            } catch (IOException ioe) {
                System.err.println("General IO Error encountered while processing file: " + ioe.getMessage() );
            }
        }
    }
    

    Note that ideally, your try...catch should wrap the smallest possible unit of code. So, wrap the FileReader separately, and "fail-fast" if the file isn't found, and wrap the readLine loop in its own try...catch. For more examples and a better explanation of how to deal with exceptions, please reference the link I provided at the top of this answer.

    Edit: issue of file path

    Not finding the file has to do with the location of the file relative to the root of the project. In your original post, you reference the file as "dichromatic.dat" but relative to the project root, it is in "src/frp/dichromatic.dat". As rpax recommends, either change the string that points to the file to properly reference the location of the file relative to the project root, or move the file to project root and leave the string as-is.

提交回复
热议问题