Is there a way to get the file name from a FileOutputStream
or from FileInputStream
?
My answer comes a little late. I hit the same issue when writing some code.
To get around it, I used a FileOutputStream(File file)
instead of FileOutputStream(String location)
because I can then do file.getAbsolutePath()
. See the example snippet below.
String location = "some.relative.path.txt";
File file = new File(location);
FileOutputStream f = new FileOutputStream(file);
String question = "<h3>"+header+"</h3>";
String finalSource = HTMLWrapper.HTML_START+question +htmlContent;
f.write(finalSource.getBytes());
f.flush();
f.close();
System.out.println("The report is now available at"+file.getAbsolutePath());
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.
This feature is not provided by the out-of-the-box File-Input/Output-Stream, but nothing stops you from writing your own subclass that stores the File (or fileName) and provides a getter for it.
I would suggest implementing some FileNameAware
interface for this), as I/O Streams are usually referenced with the InputStream
/ OutputStream
abstract classes to avoid coupling your application with specific implementations.
Possible, with reflection: Tom G answer is correct, i.e. there is no API to get the path. However, if you are stuck like me with a framework you cannot change and cannot get the filename by any other mean, you can use reflection to get the path (in my case, I needed that for debugging purposes).
Field pathField = FileOutputStream.class.getDeclaredField("path");
pathField.setAccessible(true);
String path = (String) pathField.get(outputStream);
Obviously, the implementation of FileOutpuStream could change with time and this code could break. Also, I omitted the handling of exceptions in the snippet above for clarity purposes.
Not available in 1.6 and 1.7 Confirmed available in 1.8.
Looks like the answer is no:
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileOutputStream.html
http://docs.oracle.com/javase/7/docs/api/index.html?java/io/FileOutputStream.html
There are no public methods that return the File
or String
used in construction of the stream.
EDIT: The same holds for FileInputStream
.