Java 获取 FileWriter 中的文件名

Java Get name of File in FileWriter

我想知道,在 Java 中是否可以提取 File 对象或至少提取 FileWriter 中使用的文件名作为字符串?我查看了文档,据我所知这是不可能的,但我在这方面经常是错的。

不胜感激!

您可以从 FileWriter class 扩展,为 file/filename 提供 getter:

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
}