Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

file io - Java error: Default constructor cannot handle exception type FileNotFound Exception

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 for something similar, and this is the code I found:

File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

The line I marked "ERROR" gives me an error that says "Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor."

I've searched for this error message, but everything I find seems to be unrelated to my situation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...