Android java获取路径中文件名

       平常时,我们多少都会接触到文件的使用情况,例如从手机的图库去取图片和视频,但是用intent调用,一般直接回返回来的一长串的地址,我们刚好需要的是文件名+后缀,等一些形式,这样子,就有时候我们就不知道怎么下手了,但是有的人也会说,用正则表达式也可以啊,的确可以,但是我想我自己找网上找的别人的一些,不错的方法,也值得我们学习。也是我自己实际项目中用到的,就记录一下,方便自己学习。

    上码:

       

    public class GetFileName {
        public String getFileName(String pathandname) {
            /**
             * 仅保留文件名不保留后缀
             */
            int start = pathandname.lastIndexOf("/");
            int end = pathandname.lastIndexOf(".");
            if (start != -1 && end != -1) {
                return pathandname.substring(start + 1, end);
            } else {
                return null;
            }
        }

        /**
         * 保留文件名及后缀
         */
        public String getFileNameWithSuffix(String pathandname) {
            int start = pathandname.lastIndexOf("/");
            if (start != -1) {
                return pathandname.substring(start + 1);
            } else {
                return null;
            }
        }
    }

我们看看实际效果:

 

其他文件名也可以参考这样去获取自己想要的文件名,前提是你先要拿到这文件的路径,你才可以去调用这个方法去实现。由于知识有限,有不足的,可以在【评论区】留意,我们一起去探讨学习,谢谢。

猜你喜欢

转载自blog.csdn.net/qq_36771930/article/details/89248965