4

Can I get the associated file out of a FileInputStream or a FileOutputStream? I want to tell if they are pointing to the same file. But basically I want to see if I can get a reference to the File that belongs to the FileInputStream or FileOutputStream. Is there a class like that I can use? Or can I get it out of FileInputStream or FileOutputStream?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
JoshJ
  • 81
  • 3
  • 3
    The answer appears to be no. See here: http://stackoverflow.com/questions/4930111/get-file-name-from-fileoutputstream – Trevor Freeman Jul 31 '13 at 16:33
  • Oh, ok. So it looks like I have to write my own FileInputStream or FileOutputStream class that has a reference to the File in it? I guess I can do that. Thank you! – JoshJ Jul 31 '13 at 16:35

1 Answers1

4

This is what I did:

public class FileAwareFileInputStream extends FileInputStream {
    private File file;

    public FileAwareFileInputStream(File file) throws FileNotFoundException {
        super(file);
        this.file = file;
    }

    public File getFile() {
        return this.file;
    }
}

And similarly for FileOutputStream.

JoshJ
  • 81
  • 3
  • I agree, nice workaround. However ... I think that it is likely that FileInputStream is not a class that was designed for inheritance. Extending such a class across a package boundary can make your application fragile because you can become dependent upon the implementation details of FileInputStream. I kindly suggest that, rather than extending FileInputStream, you use FileAware as a wrapper class and make FileInputStream a member field of your wrapper. You'll need to do method forwarding. In this way, you favor composition over inheritance (Joshua Bloch, Java Essentials, 2nd Ed.). – scottb Jul 31 '13 at 17:09
  • Hi, I wanted to do that, but there are methods that use this and they need it to be of type InputStream, so I cannot use it as a wrapper. I do agree composition is better though. Also this class is used internally and in a very small area and not visible to anyone else in the codebase so I think the fragility could be limited. – JoshJ Jul 31 '13 at 17:31