Java error: Default constructor cannot handle exception type FileNotFound Exception

前端 未结 3 1565
醉话见心
醉话见心 2021-01-01 07:04

I\'m trying to read input from a file to be taken into a Java applet to be displayed as a Pac-man level, but I need to use something similar to getLine()... So I searched fo

相关标签:
3条回答
  • 2021-01-01 07:40

    Either declare a explicit constructor at your subclass that throws FileNotFoundException:

    public MySubClass() throws FileNotFoundException {
    } 
    

    Or surround the code in your base class with a try-catch block instead of throwing a FileNotFoundException exception:

    public MyBaseClass()  {
        FileInputStream fstream = null;
        try {
            File inFile = new File("textfile.txt");
            fstream = new FileInputStream(inFile);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            // Do something with the stream
        } catch (FileNotFoundException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                // If you don't need the stream open after the constructor
                // else, remove that block but don't forget to close the 
                // stream after you are done with it
                fstream.close();
            } catch (IOException ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }  
    } 
    

    Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.

    0 讨论(0)
  • 2021-01-01 07:47

    You need to surround your code with try and catch as follows:

    try {
        File inFile = new File("textfile.txt");
        FileInputStream fstream = new FileInputStream(inFile);//ERROR
    } catch (FileNotFoundException fe){
        fe.printStackTrace();
    }
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    
    0 讨论(0)
  • 2021-01-01 07:54

    This is guesswork as we don't have the complete code.

    From the Javadoc:

    public FileInputStream(File file) throws FileNotFoundException
    

    It means that when you do a new FileInputStream() like you do, it can come back with a FileNotFoundException. This is a checked exception, that you need to either rethrow (i.e. add 'throws FileNotFoundException' in the method where you do the new) or catch (see other try/catch responses).

    0 讨论(0)
提交回复
热议问题