Search code examples
javaarraysfilefilenamesfilewriter

Java Get name of File in FileWriter


I was wondering, in Java is it at all possible to pull the File object or at least the name the file used in a FileWriter as a string? I looked through the documentation and as far as I can tell it isn't possible, but I'm often wrong on this stuff.

Help would be greatly appreciated!


Solution

  • You could extend from FileWriter class, provide a getter for file/filename:

    public class MyFileWriter extends FileWriter {
        private File file;
        private boolean append = false;
    
        public MyFileWriter(File file) throws IOException {
            this(file, false);
        }
        public MyFileWriter(File file, boolean append) throws IOException {
            super(file, append);
            this.file = file;
            this.append = append;
        }
        public MyFileWriter(String fileName) throws IOException {
            this(new File(fileName));
        }
        public MyFileWriter(String fileName, boolean append) throws IOException {
            this(new File(fileName), append);
        }
    // getters/setters
    }