Android通過文件路徑如何得到文件相關(guān)信息,如 文件名稱,文件大小,創(chuàng)建時(shí)間,文件的相對(duì)路徑,文件的絕對(duì)路徑等。
如圖:

image
public class MainActivity extends Activity {
private String path = "/storage/emulated/0/Android/data/cn.wps.moffice_eng/mm.doc";
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
@SuppressLint("SimpleDateFormat")
private void initView() {
// TODO Auto-generated method stub
mTextView = (TextView) findViewById(R.id.textview);
File f = new File(path);
if (f.exists()) {
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
String time = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date(f.lastModified()));
System.out.println("文件文件創(chuàng)建時(shí)間" + time);
System.out.println("文件大小:" + ShowLongFileSzie(f.length()));// 計(jì)算文件大小
// B,KB,MB,
System.out.println("文件大小:" + fis.available() + "B");
System.out.println("文件名稱:" + f.getName());
System.out.println("文件是否存在:" + f.exists());
System.out.println("文件的相對(duì)路徑:" + f.getPath());
System.out.println("文件的絕對(duì)路徑:" + f.getAbsolutePath());
System.out.println("文件可以讀取:" + f.canRead());
System.out.println("文件可以寫入:" + f.canWrite());
System.out.println("文件上級(jí)路徑:" + f.getParent());
System.out.println("文件大?。? + f.length() + "B");
System.out.println("文件最后修改時(shí)間:" + new Date(f.lastModified()));
System.out.println("是否是文件類型:" + f.isFile());
System.out.println("是否是文件夾類型:" + f.isDirectory());
mTextView.setText("文件文件創(chuàng)建時(shí)間:" + time + "\n" + "文件大小:"
+ ShowLongFileSzie(f.length()) + "\n" + "文件名稱:"
+ f.getName() + "\n" + "文件是否存在:" + f.exists() + "\n"
+ "文件的相對(duì)路徑:" + f.getPath() + "\n" + "文件的絕對(duì)路徑:"
+ f.getAbsolutePath() + "\n" + "文件可以寫入:" + f.canWrite()
+ "\n" + "是否是文件夾類型:" + f.isDirectory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/****
* 計(jì)算文件大小
*
* @param length
* @return
*/
public String ShowLongFileSzie(Long length) {
if (length >= 1048576) {
return (length / 1048576) + "MB";
} else if (length >= 1024) {
return (length / 1024) + "KB";
} else if (length < 1024) {
return length + "B";
} else {
return "0KB";
}
}
}
不要忘記在AndroidManifest.xml加權(quán)限哦!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
源碼點(diǎn)擊下載:https://github.com/DickyQie/android-file