Heir to FileInputStream Java

Question:

The task is to write a class that will accept the file name in the constructor, if the file has the .txt extension, then create a FileInputStream object, if not, throw an exception. I tried at the very beginning to check for extension, if txt, then call the constructor of the superclass, if not, then throw an exception, but ide swears that I must call the constructor of the superclass with the first line.

public class TxtInputStream extends FileInputStream {
    FileInputStream fileInputStream;

    public TxtInputStream(String fileName) throws FileNotFoundException, UnsupportedFileNameException, IOException {
        String [] fileNameArray = fileName.split(" ");
        if (fileNameArray[fileNameArray.length].equals("txt"))
            this.fileInputStream = new FileInputStream(fileName);
        else {
            throw new UnsupportedFileNameException();
            super.close();
        }
    }

    public static void main(String[] args) {
    }

}

UPD add requirements to the task:

1. The TxtInputStream class must inherit from the FileInputStream class .

2. If a txt file is passed to the constructor, the TxtInputStream should behave like a normal FileInputStream.

3. If a non-txt file is passed to the constructor, an UnsupportedFileNameException should be thrown.

4. In case of a thrown exception, super.close () should also be called.

Answer:

If inherited, then remove the variable FileInputStream fileInputStream;

and the constructor will look like this:

 public TxtInputStream(String fileName) throws FileNotFoundException, UnsupportedFileNameException, IOException {
    super(fileName);
    if(!fileName.endsWith("txt")){
        throw new UnsupportedFileNameException();
    }
}

If you need to do it as a wrapper:

then we remove the inheritance and leave the FileInputStream fileInputStream; variable FileInputStream fileInputStream; , just make it private.

then the constructor looks like this:

public TxtInputStream(String fileName) throws FileNotFoundException, UnsupportedFileNameException, IOException {
    if(fileName.endsWith("txt"))
        fileInputStream = new FileInputStream(fileName);
    else{
        throw new UnsupportedFileNameException();
    }
}

but in this case, you need to create the methods you want and redirect them to the fileInputStream object.

Scroll to Top
AllEscort