Let's assume that I have a valid Java FileDescriptor
which I got in this way:
FileInputStream is = new FileInputStream("/some/path/to/file.txt");
FileDescriptor fd = is.getFD();
Now please forget that I know file path. The only thing I have is a FileDescriptor
. Is there a simple way to know the file size?
For now I've checked that:
FileDescriptor
has valid()
method which can tell me if it's valid
but doesn't have length()
or size()
functionality.FileInputStream
doesn't return the path and since it's a stream it
obviously won't tell me the file size.File
(http://docs.oracle.com/javase/7/docs/api/java/io/File.html)
which has length()
method doesn't have a constructor able to handle
FileDescriptor.I know that I could read whole stream and sum the length but I don't consider it as simple way.
A simple way would be to get the size of the FileChannel
(refer to this question):
public long getSize(FileDescriptor fd) throws IOException {
try (FileInputStream fis = new FileInputStream(fd)) {
return fis.getChannel().size();
}
}
However, as said the linked question, there is no strong guarantee that this will work for all OS.
The only sure and compatible way is to read the content of the stream, like you said in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With