android根目录获取

目前在看一些清理工具类的软件,想着怎么样能获得android的根目录,网上有很多相关的,像sd卡外接设备的根目录,应用的缓存根目录等,但都不是我想要的,忘记从哪看的了,有这样一种写法可以实现我想要的,所以写下来记录一下,以免后边忘记。

new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try{
						File file = new File("/");
						if(null != file){
							if(file.isDirectory()){
								File[] files = file.listFiles();
								for (int i = 0; i < files.length; i++) {
									if(null != files[i]){
										Logger.iLog(TAG, "path="+files[i].getPath());
									}
								}
							}else{
								Logger.iLog(TAG, "path="+"/");
							}
						}
					}catch(Exception e){
						Logger.iLog(TAG, "file is null");
					}
				}
			}).start();

功能实现了,我就想为啥一个斜线就可以代表根目录,就进到file的源码看了下,发现new File(String path) 会调用fixSlashes()方法,

// Removes duplicate adjacent slashes and any trailing slash.
    private static String fixSlashes(String origPath) {
        // Remove duplicate adjacent slashes.
        boolean lastWasSlash = false;
        char[] newPath = origPath.toCharArray();
        int length = newPath.length;
        int newLength = 0;
        for (int i = 0; i < length; ++i) {
            char ch = newPath[i];
            if (ch == '/') {
                if (!lastWasSlash) {
                    newPath[newLength++] = separatorChar;
                    lastWasSlash = true;
                }
            } else {
                newPath[newLength++] = ch;
                lastWasSlash = false;
            }
        }
        // Remove any trailing slash (unless this is the root of the file system).
        if (lastWasSlash && newLength > 1) {
            newLength--;
        }
        // Reuse the original string if possible.
        return (newLength != length) ? new String(newPath, 0, newLength) : origPath;
    }

不过看这个方法也只是处理下多个斜线的冲突,没我想象中的特别。我又注意到file.listFiles(),子文件是通过这个方法返回的,所以去看下这个方法,结果发现关键点是native方法处理的,所以又想着会不会跟linux有关,网上一搜,果然只有一个斜线表示根目录root,在adb里边验证root下的子目录文件跟上述方法返回的根目录子文件一模一样,到这里我才想起来好像这是个很基础的知识,不过没记住只能重新温习一遍了,代价真大。

另外,各个子目录是做什么用的,我看到一篇文章,描述虽然不全,但也可以参考理解下,链接如下:

http://blog.csdn.net/brian512/article/details/41513685

你可能感兴趣的:(开发笔记)