文件操作工具类 FileUtils.java

public class FileUtils {
    
    

    public static boolean deleteDir(File dir) throws RuntimeException {
    
    
        if (dir.isDirectory()) {
    
    
            String[] children = dir.list();
            if (children == null) {
    
    
                return false;
            }
            for (int i = 0; i < children.length; i++) {
    
    
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
    
    
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除,最后剩下空目录不删除
        return dir.delete();
    }

	public static boolean isEmptyDir(File dir) throws RuntimeException {
    
    
        if (dir.isDirectory()) {
    
    
            String[] children = dir.list();
            if (children != null && children.length != 0) {
    
    
                return false;
            }
        }
        return true;
    }

/**
     * 文件移动
     * 源文件不存在renameTo方法返回false但不会报错,所以在工具方法中加入主动检查源文件逻辑;
     * 目标文件如果存在,会被默认覆盖;
     *
     * @param oldPath 文件/文件夹全路径
     * @param newPath 文件/文件夹全路径
     */
    public static boolean renameFileTo(String oldPath, String newPath) {
    
    
        Log.d(TAG, "renameFileTo: oldPath=" + oldPath + " newPath=" + newPath);
        File source = new File(oldPath);
        if (!source.exists()) {
    
    
            Log.d(TAG, "renameFileTo: Source file not exits!");
            return false;
        }
        File target = new File(newPath);
        File targetPatenFile = target.getParentFile();
        if (!targetPatenFile.exists()) {
    
    
            boolean mkdirResult = targetPatenFile.mkdirs();
            Log.d(TAG, "renameFileTo: Target parent file not exits! targetPatenFile=" + targetPatenFile);
            Log.d(TAG, "renameFileTo: Target parent file mkdir! mkdirResult=" + mkdirResult);
        }
        boolean result = source.renameTo(target);
        Log.d(TAG, "renameFileTo: result=" + result);
        return result;
    }

    /**
     * 目录拷贝
     * @param source
     * @param target
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void copyFolder(String source, String target) {
    
    
        final Path sourcePath = Paths.get(source);
        final Path targetPath = Paths.get(target);
        try {
    
    
            Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
    
    
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    
    
                    Path targetFile = targetPath.resolve(sourcePath.relativize(file));
                    Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    
    
                    Path targetDir = targetPath.resolve(sourcePath.relativize(dir));
                    Files.createDirectory(targetDir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
    
    
            Log.d(TAG, "copyFolder:IOException: " + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * 压缩多个文件到一个zip包
     *
     * @param filePaths     需要压缩的文件列表
     * @param targetZipPath 目标zip包路径
     * @throws IOException
     */
    public static void zipFiles(List<String> filePaths, String targetZipPath) throws IOException {
    
    
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(targetZipPath))) {
    
    
            for (String filePath : filePaths) {
    
    
                File file = new File(filePath);
                try (FileInputStream fileInputStream = new FileInputStream(file)) {
    
    
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    zipOutputStream.putNextEntry(zipEntry);
                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = fileInputStream.read(bytes)) >= 0) {
    
    
                        zipOutputStream.write(bytes, 0, length);
                    }
                }
            }
        }
    }
    
	public static String loadFileAsString(String filePath) {
    
    
        if (TextUtils.isEmpty(filePath)) {
    
    
            return null;
        }
        File file = new File(filePath);
        return loadFileAsString(file);
    }

    private static String loadFileAsString(File file) {
    
    
        FileInputStream fis = null;
        try {
    
    
            fis = new FileInputStream(file);
            int total = fis.available();
            byte[] dataBytes = new byte[total];
            int len = fis.read(dataBytes);
            if (total == len) {
    
    
                return new String(dataBytes);
            }
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            IOUtils.close(fis);
        }
        return null;
    }

}

猜你喜欢

转载自blog.csdn.net/u013168615/article/details/128576234