android File文件工具类

这篇文章详细介绍了Android中的FileUtils类,包括移动文件、复制文件、删除文件以及检查文件是否存在等方法,展示了处理文件操作的实用工具类实现。
摘要由CSDN通过智能技术生成


import android.os.Environment;
import android.util.Log;

import com.pax.commonlib.utils.LogUtils;
import com.pax.linkdata.cmd.LinkException;
import com.pax.pay.constant.Constants;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;



public class FileUtils {
    private static final String TAG = "FileUtils";
    private static String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"Link"
            + File.separator +"testt.txt";
    public static void moveFile(File srcFile, File destFile) throws IOException {
        if (srcFile == null) {
            throw new NullPointerException("Source must not be null");
        } else if (destFile == null) {
            throw new NullPointerException("Destination must not be null");
        } else if (!srcFile.exists()) {
            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
        } else if (srcFile.isDirectory()) {
            throw new IOException("Source '" + srcFile + "' is a directory");
        } else if (destFile.exists()) {
            throw new IOException("Destination '" + destFile + "' already exists");
        } else if (destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' is a directory");
        } else {
            boolean rename = srcFile.renameTo(destFile);
            if (!rename) {
                copyFile(srcFile, destFile);
                if (!srcFile.delete()) {
                    deleteQuietly(destFile);
                    throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'");
                }
            }

        }
    }

    public static void copyFile(File srcFile, File destFile) throws IOException {
        copyFile(srcFile, destFile, true);
    }

    public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (srcFile == null) {
            throw new NullPointerException("Source must not be null");
        } else if (destFile == null) {
            throw new NullPointerException("Destination must not be null");
        } else if (!srcFile.exists()) {
            throw new IOException("Source '" + srcFile + "' does not exist");
        } else if (srcFile.isDirectory()) {
            throw new IOException("Source '" + srcFile + "' exists but is a directory");
        } else if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
            throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
        } else {
            File parentFile = destFile.getParentFile();
            if (parentFile != null && !parentFile.mkdirs() && !parentFile.isDirectory()) {
                throw new IOException("Destination '" + parentFile + "' directory cannot be created");
            } else if (destFile.exists() && !destFile.canWrite()) {
                throw new IOException("Destination '" + destFile + "' exists but is read-only");
            } else {
                doCopyFile(srcFile, destFile, preserveFileDate);
            }
        }
    }

    private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        } else {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            FileChannel input = null;
            FileChannel output = null;

            try {
                fis = new FileInputStream(srcFile);
                fos = new FileOutputStream(destFile);
                input = fis.getChannel();
                output = fos.getChannel();
                long size = input.size();
                long pos = 0L;

                for(long count = 0L; pos < size; pos += output.transferFrom(input, pos, count)) {
                    count = size - pos > 31457280L ? 31457280L : size - pos;
                }
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {

                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {

                    }
                }
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {

                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {

                    }
                }
            }

            if (srcFile.length() != destFile.length()) {
                throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
            } else {
                if (preserveFileDate) {
                    destFile.setLastModified(srcFile.lastModified());
                }

            }
        }
    }

    public static boolean deleteQuietly(File file) {
        if (file == null) {
            return false;
        } else {
            try {
                if (file.isDirectory()) {
                    cleanDirectory(file);
                }
            } catch (Exception var3) {
            }

            try {
                return file.delete();
            } catch (Exception var2) {
                return false;
            }
        }
    }

    public static void cleanDirectory(File directory) throws IOException {
        String message;
        if (!directory.exists()) {
            message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        } else if (!directory.isDirectory()) {
            message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        } else {
            File[] files = directory.listFiles();
            if (files == null) {
                throw new IOException("Failed to list contents of " + directory);
            } else {
                IOException exception = null;
                File[] arr$ = files;
                int len$ = files.length;

                for(int i$ = 0; i$ < len$; ++i$) {
                    File file = arr$[i$];

                    try {
                        forceDelete(file);
                    } catch (IOException var8) {
                        exception = var8;
                    }
                }

                if (null != exception) {
                    throw exception;
                }
            }
        }
    }

    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file);
        } else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent) {
                    throw new FileNotFoundException("File does not exist: " + file);
                }

                String message = "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }

    }

    public static void deleteDirectory(File directory) throws IOException {
        if (directory.exists()) {
            if (!isSymlink(directory)) {
                cleanDirectory(directory);
            }

            if (!directory.delete()) {
                String message = "Unable to delete directory " + directory + ".";
                throw new IOException(message);
            }
        }
    }

    public static boolean isSymlink(File file) throws IOException {
        if (file == null) {
            throw new NullPointerException("File must not be null");
        } else {
            File fileInCanonicalDir = null;
            if (file.getParent() == null) {
                fileInCanonicalDir = file;
            } else {
                File canonicalDir = file.getParentFile().getCanonicalFile();
                fileInCanonicalDir = new File(canonicalDir, file.getName());
            }

            return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
        }
    }

    public static void setPropertiesTxt(boolean videoStates,boolean imageStates){

            new Thread(){
                @Override
                public void run() {
                    try {
                        File file = new File(filePath);
                        if (file.exists()){
                            file.delete();
                        }
                        String data = "{\"playVideo\":\"" +
                                videoStates+
                                "\",\"playImage\":\""+imageStates+"\"}";
                        FileWriter fw = new FileWriter(filePath, true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(data);// 往已有的文件上添加字符串
                        bw.close();
                        fw.close();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }.start();
    }
    public static void delFile(String filePath){
        boolean delete = new File(filePath).delete();
        if (delete){

        }
    }
    /**
     * 遍历目录下所有文件,并输出包含文件名的列表
     *
     * @param parentPath
     * @return parentPath目录下所有文件的文件名
     */
    public static List<String> getAllFiles(String parentPath) throws LinkException {
        if (parentPath == null) {
            return null;
        }
        List<String> allFiles = new ArrayList<>();
        File parent = new File(parentPath);
        if (!parent.exists()) {
            return null;
        }
        if (!parent.isDirectory()) {
            throw new LinkException(LinkException.ERR_FILE_NO_EXIST, "Parameter is not directory!");
        }
        File[] files = parent.listFiles();
        if (files == null || files.length <= 0) {
            return null;
        }
        for (File file : files) {
            if (!file.isDirectory()) {
                String filePath = file.getName();
                allFiles.add(filePath);
            }
        }
        return allFiles;
    }


    /**
     * 通过文件名判断指定目录中是否有此文件
     */
    public static boolean isFileExists(String fileName,String directoryName) throws LinkException {
        List<String> allFiles = getAllFiles(directoryName);
        if (allFiles != null && allFiles.size() >0){
            for (int i = 0; i < allFiles.size(); i++) {
                if (allFiles.get(i).equals(fileName)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 删除File文件(输入指定的文件不删除,其它全部删除)
     */
    public static void delOtherFiles(String fileName,String directoryPath){
        try {
            List<String> allFiles = getAllFiles(directoryPath);
            if (allFiles != null && allFiles.size() >0){
                for (int i = 0; i < allFiles.size(); i++) {
                    if (allFiles.get(i).equals(fileName)){
                    }else {
                        delFile(directoryPath+allFiles.get(i));
                    }
                }
            }
        } catch (LinkException e) {
            LogUtils.e(TAG, e);
        }
    }
}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值