Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

java - Get the file size in android sdk?

I have a problem getting the size of a file. I have the following code:

File file = new File("/sdcard/lala.txt");
long length = file.length();

And always length is zero, yes zero.

I am using Android SDK (not sure what version), the code is running inside an Activity, I have created an sdcard.

Perhaps it is a permission issue? Is there anything I am missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The File.length() method returns the following according to the javadoc:

"The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes."

As you can see, zero can be returned:

  • if the file exists but contained zero bytes.
  • if the file does not exist, or
  • if the file is some OS-specific special file.

My money is on the second case; i.e. that you have the wrong filename / pathname. Try calling File.exists() on the filename to see what that tells you. The other two cases are possible too, I guess.

(For the record, most /proc/... files on a Linux-based system also have an apparent file size of zero. And Android is Linux based.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...