java Android Uri 到文件大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5263444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:18:36  来源:igfitidea点击:

Android Uri to Filesize

javaandroidurifilesize

提问by Soccertrash

Possible Duplicate:
Android: Get the size of a file in resources?

可能的重复:
Android:获取资源中文件的大小?

I want to upload a file to a WebServer. To show the progress of the upload I need to know the complete size of the file. Since I have only the Uri of the file (got it from an Intent), I have no chance to get at the file's size. My workaround is to open an InputStream and count the bytes that are read on this InputStream. But this is circuitous. Is there an easier/conventional way to solve this issue?

我想将文件上传到 WebServer。要显示上传进度,我需要知道文件的完整大小。由于我只有文件的 Uri(从 Intent 获取),我没有机会获得文件的大小。我的解决方法是打开一个 InputStream 并计算在这个 InputStream 上读取的字节数。但这是迂回的。有没有更简单/传统的方法来解决这个问题?

Thanks

谢谢

回答by fredley

You can get the size of the file in bytes thus:

您可以通过以下方式获取文件的大小(以字节为单位):

File f = new File(uri.getPath());
long size = f.length();