<Android> 文件夹和文件操作

接下来的例子说的是Android外部SD卡中的文件拷贝到内部SD卡.

    private static final String TAG = "MyTag";
    private static final String EXTSD_PATH = "/mnt/extsd/my/dir";
    private static final String SDCARD_PATH = "/sdcard/my/dir";
    private boolean needReboot = false;

	
    /**
     * 删除目录及目录下的文件
     *
     * @param dir
     *            要删除的目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = _deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            Log.i(TAG, String.format("Delete %s failed!", dir));
            return false;
        }

        Log.i(TAG, String.format("Empty %s success", dir));
        return true;
    }
    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public boolean _deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.i(TAG, String.format("Delete %s success", fileName));
                return true;
            } else {
                Log.i(TAG, String.format("Delete %s failed!", fileName));
                return false;
            }
        }
        return false;
    }
    private boolean sameFile(File srcFile, File destFile)  throws IOException{
        FileInputStream src = new FileInputStream(srcFile);
        FileInputStream dest = new FileInputStream(destFile);
        int destLen = 0, srcLen = 0;
        byte[] srcBuf = new byte[1024];
        byte[] destBuf = new byte[1024];
        int i;
        boolean same = true;
		while ((srcLen = src.read(srcBuf)) != -1) {
            destLen = dest.read(destBuf);
            if (srcLen != destLen) {
                Log.e(TAG, String.format("lens: %d != %d", srcLen, destLen));
                same = false;
                break;
            }
            for (i = 0; i < srcLen; i++) {
                if (srcBuf[i] != destBuf[i]) {
                    Log.e(TAG, String.format("value: %02X != %02X", srcBuf[i], destBuf[i]));
                    same = false;
                    break;
                }
            }
        }
        if ((srcLen != -1)) {
            Log.e(TAG, String.format("error len: %d", srcLen));
		}
        dest.close();
        dest.close();

        return same;
    }

    /**
     * 拷贝一个文件,srcFile源文件,destFile目标文件
     *
     * @throws IOException
     */
    public boolean copyFileTo(File srcFile, File destFile) throws IOException {
        if (srcFile.isDirectory() || destFile.isDirectory())
            return false;// 判断是否是文件

        if (!srcFile.getAbsolutePath().contains(".txt") &&
                !srcFile.getAbsolutePath().contains(".TXT") &&
                !srcFile.getAbsolutePath().contains(".ini") &&
                !srcFile.getAbsolutePath().contains(".INI")) {
            return true;
        }
        if (destFile.exists()) {
            if (sameFile(srcFile, destFile)) {
                Log.i(TAG, String.format("same file %s", srcFile.getName()));
                return true;
            }
        } else {
            Log.i(TAG, String.format("%s not exist", destFile.getName()));
        }
        deleteDirectory(destFile.getParent());
		destFile.createNewFile();

        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        int readLen ;
        byte[] buf = new byte[1024];
        while ((readLen = fis.read(buf)) != -1) {
            fos.write(buf, 0, readLen);
        }
        fos.flush();
        fos.close();
        fis.close();
		if (sameFile(srcFile, destFile)) {
			needReboot = true;
			Log.i(TAG, String.format("copy file %s to %s success",
							srcFile.getAbsolutePath(), destFile.getAbsolutePath()));
		} else {
			Log.i(TAG, String.format("copy file %s to %s failed!",
							srcFile.getAbsolutePath(), destFile.getAbsolutePath()));
		}
        return true;
    }
    /**
     * 拷贝目录下的所有文件到指定目录
     *
     * @param srcDir
     * @param destDir
     * @return
     * @throws IOException
     */
    public boolean copyFilesTo(File srcDir, File destDir) throws IOException {
        if (!destDir.exists()) {
            destDir.mkdirs();
            if (!destDir.exists()) {
                Log.i(TAG, String.format("create dir %s failed!", destDir.getName()));
                return false;// 判断目标目录是否存在
            }
        }
        if (!srcDir.isDirectory() || !destDir.isDirectory())
            return false;// 判断是否是目录

        File[] srcFiles = srcDir.listFiles();
        for (int i = 0; i < srcFiles.length; i++) {
            if (srcFiles[i].isFile()) {
                // 获得目标文件
                File destFile = new File(destDir.getPath() + "//"
                        + srcFiles[i].getName());
                copyFileTo(srcFiles[i], destFile);
            } else if (srcFiles[i].isDirectory()) {
                File theDestDir = new File(destDir.getPath() + "//"
                        + srcFiles[i].getName());
                copyFilesTo(srcFiles[i], theDestDir);
            }
        }
        return true;
    }

    public boolean initSdcardTestDir() {
        File dirFile = new File(SDCARD_PATH);
        File extsdFile = new File(EXTSD_PATH);

        if (dirFile.exists() && !dirFile.isDirectory()) {
            _deleteFile(SDCARD_PATH);
            Log.i(TAG, "sdcard test Dir invalid, delete");
        }

        if (!Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            Log.i(TAG, "External SD not mounted!");
            return false;
        }
        if (!extsdFile.exists()) {
            Log.i(TAG, "Test Dir not exist!");
            return false;
        }
        try {
            copyFilesTo(extsdFile, dirFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
	private static final String TAG = "MyTag";
    private static final String EXTSD_PATH = "/mnt/extsd/my/dir";
    private static final String SDCARD_PATH = "/sdcard/my/dir";
    private boolean needReboot = false;

	
    /**
     * 删除目录及目录下的文件
     *
     * @param dir
     *            要删除的目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = _deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            Log.i(TAG, String.format("Delete %s failed!", dir));
            return false;
        }

        Log.i(TAG, String.format("Empty %s success", dir));
        return true;
    }
    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public boolean _deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.i(TAG, String.format("Delete %s success", fileName));
                return true;
            } else {
                Log.i(TAG, String.format("Delete %s failed!", fileName));
                return false;
            }
        }
        return false;
    }
    private boolean sameFile(File srcFile, File destFile)  throws IOException{
        FileInputStream src = new FileInputStream(srcFile);
        FileInputStream dest = new FileInputStream(destFile);
        int destLen = 0, srcLen = 0;
        byte[] srcBuf = new byte[1024];
        byte[] destBuf = new byte[1024];
        int i;
        boolean same = true;
		while ((srcLen = src.read(srcBuf)) != -1) {
            destLen = dest.read(destBuf);
            if (srcLen != destLen) {
                Log.e(TAG, String.format("lens: %d != %d", srcLen, destLen));
                same = false;
                break;
            }
            for (i = 0; i < srcLen; i++) {
                if (srcBuf[i] != destBuf[i]) {
                    Log.e(TAG, String.format("value: %02X != %02X", srcBuf[i], destBuf[i]));
                    same = false;
                    break;
                }
            }
        }
        if ((srcLen != -1)) {
            Log.e(TAG, String.format("error len: %d", srcLen));
		}
        dest.close();
        dest.close();

        return same;
    }

    /**
     * 拷贝一个文件,srcFile源文件,destFile目标文件
     *
     * @throws IOException
     */
    public boolean copyFileTo(File srcFile, File destFile) throws IOException {
        if (srcFile.isDirectory() || destFile.isDirectory())
            return false;// 判断是否是文件

        if (!srcFile.getAbsolutePath().contains(".txt") &&
                !srcFile.getAbsolutePath().contains(".TXT") &&
                !srcFile.getAbsolutePath().contains(".ini") &&
                !srcFile.getAbsolutePath().contains(".INI")) {
            return true;
        }
        if (destFile.exists()) {
            if (sameFile(srcFile, destFile)) {
                Log.i(TAG, String.format("same file %s", srcFile.getName()));
                return true;
            }
        } else {
            Log.i(TAG, String.format("%s not exist", destFile.getName()));
        }
        deleteDirectory(destFile.getParent());
		destFile.createNewFile();

        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        int readLen ;
        byte[] buf = new byte[1024];
        while ((readLen = fis.read(buf)) != -1) {
            fos.write(buf, 0, readLen);
        }
        fos.flush();
        fos.close();
        fis.close();
		if (sameFile(srcFile, destFile)) {
			needReboot = true;
			Log.i(TAG, String.format("copy file %s to %s success",
							srcFile.getAbsolutePath(), destFile.getAbsolutePath()));
		} else {
			Log.i(TAG, String.format("copy file %s to %s failed!",
							srcFile.getAbsolutePath(), destFile.getAbsolutePath()));
		}
        return true;
    }
    /**
     * 拷贝目录下的所有文件到指定目录
     *
     * @param srcDir
     * @param destDir
     * @return
     * @throws IOException
     */
    public boolean copyFilesTo(File srcDir, File destDir) throws IOException {
        if (!destDir.exists()) {
            destDir.mkdirs();
            if (!destDir.exists()) {
                Log.i(TAG, String.format("create dir %s failed!", destDir.getName()));
                return false;// 判断目标目录是否存在
            }
        }
        if (!srcDir.isDirectory() || !destDir.isDirectory())
            return false;// 判断是否是目录

        File[] srcFiles = srcDir.listFiles();
        for (int i = 0; i < srcFiles.length; i++) {
            if (srcFiles[i].isFile()) {
                // 获得目标文件
                File destFile = new File(destDir.getPath() + "//"
                        + srcFiles[i].getName());
                copyFileTo(srcFiles[i], destFile);
            } else if (srcFiles[i].isDirectory()) {
                File theDestDir = new File(destDir.getPath() + "//"
                        + srcFiles[i].getName());
                copyFilesTo(srcFiles[i], theDestDir);
            }
        }
        return true;
    }

    public boolean initSdcardTestDir() {
        File dirFile = new File(SDCARD_PATH);
        File extsdFile = new File(EXTSD_PATH);

        if (dirFile.exists() && !dirFile.isDirectory()) {
            _deleteFile(SDCARD_PATH);
            Log.i(TAG, "sdcard test Dir invalid, delete");
        }

        if (!Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            Log.i(TAG, "External SD not mounted!");
            return false;
        }
        if (!extsdFile.exists()) {
            Log.i(TAG, "Test Dir not exist!");
            return false;
        }
        try {
            copyFilesTo(extsdFile, dirFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值