android获取file文件的路径问题,Android根据文件路径使用File类获取文件相关信息...

该博客介绍了如何在Android中使用File类通过文件路径获取文件的相关信息,包括文件名称、大小、创建时间、相对路径、绝对路径等,并展示了具体的代码示例。同时,提到了在实现这些功能时需要在AndroidManifest.xml中添加相应的权限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android通过文件路径如何得到文件相关信息,如 文件名称,文件大小,创建时间,文件的相对路径,文件的绝对路径等。

如图:

b4be02469ca69c45d3d9ec8a08d7f5ca.png

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("文件文件创建时间" + time);

System.out.println("文件大小:" + ShowLongFileSzie(f.length()));// 计算文件大小

// B,KB,MB,

System.out.println("文件大小:" + fis.available() + "B");

System.out.println("文件名称:" + f.getName());

System.out.println("文件是否存在:" + f.exists());

System.out.println("文件的相对路径:" + f.getPath());

System.out.println("文件的绝对路径:" + f.getAbsolutePath());

System.out.println("文件可以读取:" + f.canRead());

System.out.println("文件可以写入:" + f.canWrite());

System.out.println("文件上级路径:" + f.getParent());

System.out.println("文件大小:" + f.length() + "B");

System.out.println("文件最后修改时间:" + new Date(f.lastModified()));

System.out.println("是否是文件类型:" + f.isFile());

System.out.println("是否是文件夹类型:" + f.isDirectory());

mTextView.setText("文件文件创建时间:" + time + "\n" + "文件大小:"

+ ShowLongFileSzie(f.length()) + "\n" + "文件名称:"

+ f.getName() + "\n" + "文件是否存在:" + f.exists() + "\n"

+ "文件的相对路径:" + f.getPath() + "\n" + "文件的绝对路径:"

+ f.getAbsolutePath() + "\n" + "文件可以写入:" + f.canWrite()

+ "\n" + "是否是文件夹类型:" + f.isDirectory());

} catch (Exception e) {

e.printStackTrace();

}

}

}

/****

* 计算文件大小

*

* @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加权限哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值