Java: constructing a file from a URI?
I need to obtain a File object from a URI, working in Java, but keep getting a length of zero - though I know the file size is not zero.
I need the File object to pass to another constructor.
I'm not sure if it's because I'm constructing it in the wrong way? Here's my code:
File vide开发者_如何学JAVAoFile = new File(videoURI.getPath());
if (videoFile == null) {
Log.d(LOG_TAG, "File not found!");
return false;
}
Log.d(LOG_TAG, "about to upload, filepath: " + videoFile.getPath());
Log.d(LOG_TAG, "File length: " + String.valueOf(videoFile.length()));
The log output doesn't spit out 'File not found!', and prints a non-null path, but shows a length of 0.
Make sure your URI points to a file.
The videoFile will not be null because you might be creating a new file. So videoFile doesn't represent the actual file you think and that's why you get the 0 length.
File videoFile = new File(videoURI.getPath()); // videoFile != null
Try using the File constructor that takes in a URI.
If the file exists, but its length is "unexpectingly" zero, then chances are big that you created/wrote this file beforehand in the same program (or another program running in the same context), but didn't close its OutputStream
. The normal Java IO idiom is to close streams after use. Also see this Sun tutorial for an example.
One important thing to note is that the file object you get from
File videoFile = new File(videoURI.getPath());
is never going to be null, as with any object you get back from a constructor call. The only way you don't get an object back from a constructor is if the constructor throws an exception. So null checking the return as a check to see if the file exists is really doing nothing for you, if you really want to know if the file exits or not you should use videoFile.exists()
instead. The File constructor that takes a URI directly is probably going to be a better option for you as it will perform all the necessary checking to ensure that the uri can be used as a file and will correctly extract the file path from the uri.
I had fought it, too, for 4 hours. A machine-independent solution is found:
File mFile = new File(new Path(mUri.getPath()).toString);
The mFile will have correct path in win/linux/mac and can work normally.
精彩评论