Get file name from FileOutputStream

后端 未结 5 1061
别那么骄傲
别那么骄傲 2020-11-29 09:52

Is there a way to get the file name from a FileOutputStream or from FileInputStream?

5条回答
  •  孤独总比滥情好
    2020-11-29 10:25

    This is not possible, even in principle. The assumption of the question is that each file input stream is associated with one file that has one name. The latter assumption is wrong, for POSIX systems. For POSIX systems, a file can have any number of names (hard links), including zero. The case of zero names is quite common for temporary files, to ensure that the temporary file is removed on program exit.

    I've written plenty of file IO code, and never needed this functionality. That you are asking for it suggests you have a design flaw. That is, you have an XY problem.

    • There is almost no reason for code to declare the class of a reference to a stream object to be a file stream. IO code can use an InputStream or OutputStteam. Indeed, it should, as part of programming to an interface, and to enable cheap unit testing of your IO code (by enabling use of a simple byte array stream as a mock object).
    • Are you perhaps hoping to use the filename in some log messages? If so, that suggests you are trying to log file IO errors too low in your program hierarchy. Perhaps you are catching IOExceptions too "early", rather than letting them propagate to higher parts of your program, which know that the IO is file IO and know the name of the file.

提交回复
热议问题