0

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!

6
  • Its rare to be in a situation where you are handed a FileWriter but dont know where you are writing. Commented May 11, 2020 at 20:55
  • Do I understand correctly, you have FileWritter reference but don't have File ? Commented May 11, 2020 at 21:17
  • Simply put: no. FileWriter doesn’t have any methods at all, in fact, except for those inherited from other classes. Commented May 11, 2020 at 21:39
  • My code needs to be really efficient with regards to what it is doing. It's cycling hundreds of thousands of times, so I pass it a FileWriter instead of a File so i don't need to create a new FileWriter object every cycle. Theoretically i could also pass it the File as another parameter, however i'd only use it to grab the name, which seems unnecessary to me. Commented May 11, 2020 at 21:57
  • 1
    I suggest you use a wrapper class which contains a reference to both the Writer and the File. Probably also improves the readability of the code. Alternatively, you could store the File path in a ThreadLocal (in case your app is multithreaded) or a static field. Not very elegant, but it would probably work. Commented May 11, 2020 at 22:19

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh that's a clever solution. I like that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.