确保路径存在的函数 ensurePathExist

8 篇文章 0 订阅

        不管什么系统,很多文件操作得在保证文件(夹)路径存在的前提下才能进行。Symbian 提供了ensurePathExist函数,但Java API似乎没有相应的功能,所以只好自己搞一个了。考虑到使用程度较高,所以决定写点测试。有什么补充,欢迎提出。

        废话少说,先上源码

static boolean ensurePathExist(String file) {
        File f = new File(file).getAbsoluteFile();

        if (f.exists()) {
            return true;
        }

        String separator;
        if (File.separator.equals("\\")) {
            separator = "\\\\";
        } else {
            //此分支未曾测试,应该是Linux/Unix下才会执行到
            separator = "/";
        }
        String[] strs = f.getAbsolutePath().split(separator);

        File path;
        String lastSnippet = strs[strs.length - 1];
        int lastIndex = lastSnippet.lastIndexOf(".");
        // "C:\abc\ef\file.txt"  not "C:\abc\ef\file.txt."
        if (lastIndex >= 0 && lastIndex < lastSnippet.length() - 1) {
            path = f.getAbsoluteFile().getParentFile();
        } //"C:\abc\ef\dir"
        else {
            path = f.getAbsoluteFile();
        }
        path.mkdirs();

        return path.exists();
    }

测试用例,因为偷懒,没有使用自动化工具,后来发现这完全是个错误……


        ArrayList<String> p = new ArrayList<String>();
        p.add("D:\\nonexist\\nonexist\\file");
        p.add("D:\\nonexist\\nonexist\\file.mp3");
        p.add("file.mp3");
        p.add("file");
        p.add("D:\\");
        p.add("D:"); //5
        p.add("\\");
        p.add(".");
        p.add(".\\file");
        p.add("..\\file");
        p.add("...\\file");//10
        p.add("D:\\nonexist.\\file");
        p.add("D:\\nonexist.");
        p.add("D:\\nonexist..");
        p.add("D:\\nonexist..\\file");
        p.add("D:\\nonexist\\fi..le");//15
        p.add("K:\\notexit");
        p.add("D:\\not/xit");
        p.add("noexist\\file");
        p.add("\\noexist\\file");
        p.add("\\noexist\\file.mp3");//20
        p.add("D:\\nonexist\\nonexist\\file.mp3\\");
        p.add("D:\\nonexist\\non....exist\\file.mp3\\\\");
        p.add("D:\\nonexist\\nonex\nist\\");
        p.add("D:\\nonexist\\\\nonexist");

        /*
         * 手工测试
         * 
         * 运行这些测试用例会发现 8,9,10是不不一样的,15,17可以运行,且能解释得通……
         * 实际上,不管这些测试用例的结果有多奇怪,都可以用操作系统来解释
         */
        System.out.println(ensurePathExist(p.get(24)));

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值