java 获取目录下所有文件及文件目录

sancaiodm Java 2021-09-01 913 0

java获取文件或文件夹内最后修改时间:

    /**
     * @param file
     *            File
     * @return long
     */
    public static long getFolderLastModifyTime(File file) {
        long result = 0;
        if (file == null || !file.exists()) {
            Utils.logd(TAG, "Given file not exist.");
            return result;
        }
        if (file.isFile()) {
            result = file.lastModified();
        } else {
            File[] fileList = file.listFiles();
            if (fileList == null || fileList.length == 0) {
                Utils.loge(TAG, "No sub files in folder:" + file.getAbsolutePath());
                return result;
            }
            for (File subFile : fileList) {
                long lastModifiedTime = 0;
                if (subFile.isFile()) {
                    lastModifiedTime = subFile.lastModified();
                } else {
                    lastModifiedTime = getFolderLastModifyTime(subFile);
                }
                if (lastModifiedTime > result) {
                    result = lastModifiedTime;
                }
            }
        }
        return result;
    }


java复制文件或文件 夹

    /**
     * @param sourceFilePath
     *            String
     * @param targetFilePath
     *            String
     * @return boolean
     */
    public static boolean doCopy(String sourceFilePath, String targetFilePath) {
        Utils.logi(TAG, "-->doCopy() from " + sourceFilePath + " to " + targetFilePath);
        File sourceFile = new File(sourceFilePath);
        if (null == sourceFile || !sourceFile.exists()) {
            Utils.logw(TAG,
                    "The sourceFilePath = " + sourceFilePath + " is not existes, do copy failed!");
            return false;
        }
        // Get all files and sub directories under the current directory
        File[] files = sourceFile.listFiles();
        if (null == files) {
            // Current file is not a directory
            String tagLogPath = sourceFile.getAbsolutePath();
            return copyFile(tagLogPath, targetFilePath);
        } else {
            // Current file is a directory
            File targetFile = new File(targetFilePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            for (File subFile : files) {
                doCopy(subFile.getAbsolutePath(),
                        targetFilePath + File.separator + subFile.getName());
            }
        }
        return true;
    }

    private static final int COPY_BUFFER_SIZE = 1024;

    private static boolean copyFile(String sourceFilePath, String targetFilePath) {
        Utils.logi(TAG, "-->copyFile() from " + sourceFilePath + " to " + targetFilePath);
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            Utils.logw(TAG, "The sourceFilePath = " + sourceFilePath + " is not existes, do copy failed!");
            return false;
        }

        File targetFile = new File(targetFilePath);
        if (targetFile.exists()) {
            targetFile.delete();
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(sourceFile);
            File parentFile = targetFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            LogFileManager.createNewFile(targetFile);
            fos = LogFileManager.getFileOutputStream(targetFile);
            if (fos == null) {
                return false;
            }
            byte[] temp = new byte[COPY_BUFFER_SIZE];
            int len;
            while ((len = fis.read(temp)) != -1) {
                fos.write(temp, 0, len);
            }
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }


java获取文件或文件夹的大小

	/**
     * Get file or folder size of input filePath.
     *
     * @param filePath the path of file
     * @return filePath size
     */
    public static long getFileSize(String filePath) {
        long size = 0;
        if (filePath == null) {
            return 0;
        }
        File fileRoot = new File(filePath);
        if (fileRoot == null || !fileRoot.exists()) {
            return 0;
        }
        if (!fileRoot.isDirectory()) {
            size = fileRoot.length();
        } else {
            File[] files = fileRoot.listFiles();
            // why get a null here ?? maybe caused by permission denied
            if (files == null || files.length == 0) {
                Utils.logv(TAG, "Loop folder [" + filePath + "] get a null/empty list");
                return 0;
            }
            for (File file : files) {
                if (file == null) {
                    continue;
                }
                size += getFileSize(file.getAbsolutePath());
            }
        }
        return size;
    }
	


java判断文件是否存在及是否有内容

public static boolean isFileExistOrNotEmpty(String filePath) {
    try {
        File f = new File(filePath);
        if (!f.exists() || f.length() == 0) {
            return false;
        }
    } catch (Exception e) {
        return false;
    }
    return true;
}

 

 java 获取目录下所有文件及文件目录,

    public static List<File> getAllFiles(File sourceFile, boolean containFolder) {
        Stack<File> dirStack = new Stack<File>();
        List<File> allFile = new LinkedList<File>();
        if(!sourceFile.exists()) {
            Log.e(TAG, "file: " + sourceFile + " does not exist");
            return allFile;
        }
        if (sourceFile.isDirectory()) {
            dirStack.add(sourceFile);
        } else {
            allFile.add(sourceFile);
        }
        while(!dirStack.empty()) {
            File file = dirStack.pop();
            if(containFolder) {
                allFile.add(file);
            }
            if (file != null) {
                File fileArray[] = file.listFiles();
                if(fileArray != null){
                    for(File f : fileArray ) {
                        if(f.isDirectory()) {
                            dirStack.push(f);
                        } else {
                            allFile.add(f);
                        }
                    }
                }
            }

        }
        return allFile;
    }


java压缩文件或文件夹

    /**
     * @param sourceFilePath String
     * @param targetFilePath String
     * @return boolean
     */
    public static boolean doZip(String sourceFilePath, String targetFilePath) {
        Utils.logi(TAG, "-->doZip from " + sourceFilePath + " to " + targetFilePath);
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            Utils.logw(TAG,
                    "The sourceFilePath = " + sourceFilePath + " is not existes, do zip failed!");
            return false;
        }

        File targetFile = new File(targetFilePath);
        if (targetFile.exists()) {
            LogFileManager.delete(targetFile);
        }

        ZipOutputStream outZip = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream =
                    LogFileManager.getFileOutputStream(new File(targetFilePath));
            if (fileOutputStream == null) {
                return false;
            }
            outZip = new ZipOutputStream(fileOutputStream);
            zipFile(sourceFilePath, "", outZip);
            outZip.flush();
            outZip.finish();
            fileOutputStream.close();
            outZip.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (outZip != null) {
                    outZip.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    private static final int ZIP_BUFFER_SIZE = 100 * 1024;
    private static boolean zipFile(String srcRootPath, String fileRelativePath,
            ZipOutputStream zout) {
        Utils.logd(TAG, "zipFile(), srcRootPath=" + srcRootPath
                + ", fileRelativePath = " + fileRelativePath);
        boolean result = false;
        File file = new File(srcRootPath);
        if (fileRelativePath == null || fileRelativePath.isEmpty()) {
            fileRelativePath = file.getName();
        }
        if (file.exists()) {
            if (file.isFile()) {
                FileInputStream in = null;
                try {
                    in = new FileInputStream(file);
                    ZipEntry entry = new ZipEntry(fileRelativePath);
                    zout.putNextEntry(entry);

                    int len = 0;
                    byte[] buffer = new byte[ZIP_BUFFER_SIZE];
                    while ((len = in.read(buffer)) > -1) {
                        zout.write(buffer, 0, len);
                    }
                    zout.closeEntry();
                    zout.flush();
                    result = true;
                } catch (FileNotFoundException e) {
                    Utils.loge(TAG, "FileNotFoundException", e);
                } catch (IOException e) {
                    Utils.loge(TAG, "IOException", e);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return result;
            } else {
                result = true;
                String[] fileList = file.list();
                if (fileList == null) {
                    return false;
                }
                if (fileList.length <= 0) {
                    ZipEntry entry = new ZipEntry(fileRelativePath + File.separator);
                    try {
                        zout.putNextEntry(entry);
                        zout.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                }

                for (String subFileName : fileList) {
                    String newRelativePath = fileRelativePath.isEmpty() ? subFileName
                            : (fileRelativePath + File.separator + subFileName);
                    if (!zipFile(srcRootPath + File.separator + subFileName,
                            newRelativePath, zout)) {
                        result = false;
                        Utils.loge(TAG, "File [" + subFileName + "] zip failed");
                    }
                }
                return result;
            }
        } else {
            Utils.loge(TAG, "File [" + file.getPath() + "] does not exitst");
            return false;
        }
    }


java 删除文件夹及文件夹所有文件与目录

    public static boolean deleteContentsAndDir(File dir) {
        if (deleteContents(dir)) {
            return dir.delete();
        } else {
            return false;
        }
    }

    public static boolean deleteContents(File dir) {
        File[] files = dir.listFiles();
        boolean success = true;
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    success &= deleteContents(file);
                }
                if (!file.delete()) {
                    Log.i("androidodm", "Failed to delete " + file);
                    success = false;
                }
            }
        }
        return success;
    }


java 删除某个时间前的文件 可以删除指定文件数量

    public static boolean deleteOlderFiles(File dir, int minCount, long minAgeMs) {
        if (minCount < 0 || minAgeMs < 0) {
            throw new IllegalArgumentException("Constraints must be positive or 0");
        }

        final File[] files = dir.listFiles();
        if (files == null) return false;

        // Sort with newest files first
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File lhs, File rhs) {
                return Long.compare(rhs.lastModified(), lhs.lastModified());
            }
        });

        // Keep at least minCount files
        boolean deleted = false;
        for (int i = minCount; i < files.length; i++) {
            final File file = files[i];

            // Keep files newer than minAgeMs
            final long age = System.currentTimeMillis() - file.lastModified();
            if (age > minAgeMs) {
                if (file.delete()) {
                    Log.d(TAG, "Deleted old file " + file);
                    deleted = true;
                }
            }
        }
        return deleted;
    }


java 删除文件目录

    public static void deleteAll(File target) {
        if (target.isDirectory()) {
            for (File child : target.listFiles()) {
                deleteAll(child);
            }
        }
        target.delete();
    }


java 读取文件的最后一行内容

public static String getLastLine(String filePath){
    String res = "";
    File file = new File(filePath);

    if(!file.exists()){
        return res;
    }
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(file,"r");
        long len = raf.length();
        if(len == 0L){
            return res;
        }
        long pos = len -1;
        while(pos > 0){
            pos --;
            raf.seek(pos);
            if(raf.readByte() == '\n'){
                break;
            }
        }
        if(pos == 0){
            raf.seek(0);
        }
        byte[] bytes = new byte[(int)(len - pos)];
        raf.read(bytes);
        res = new String(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if(raf != null){
                raf.close();
                raf = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return res;
}

java 保存文件 

public static boolean writeFile(String filePath, String content) {
    boolean res = true;
    File file = new File(filePath);
    File dir = new File(file.getParent());
    if (!dir.exists())
        dir.mkdirs();
    try {
        if (!file.exists()) {
            file.createNewFile();
        } else {
            file.delete();
            file.createNewFile();
        }
        FileWriter mFileWriter = new FileWriter(file, false);
        mFileWriter.write(content);
        mFileWriter.close();
    } catch (IOException e) {
        res = false;
    }
    return res;
}

java 读文件

private int readNodeValue(String file,int defaultValue){
     int vales = defaultValue;
     try{
          BufferedReader bufferedread = new BufferedReader(new FileReader(filepath));
          value  = Interger.parseInt(bufferedread.readLine(),10)
          bufferedread.close(); 
     }catch(Exception e){
       e.getMessage();
     }
     return value;
}


java 保存文件 

public static long readFileToSaveNewFile(FileInputStream fis, String destFilePath) throws Exception {
        if (fis == null || destFilePath == null)
            return -1;
        long totalLen = 0;
        BufferedInputStream bin = null;
        BufferedOutputStream bout = null;
        File destFile = new File(destFilePath);
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(destFile);
        try {
            try {
                bin = new BufferedInputStream(fis, 1024);
                bout = new BufferedOutputStream(fos, 1024);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = bin.read(buffer)) > 0) {
                    bout.write(buffer, 0, len);
                    totalLen += len;
                }
            } finally {
                if (null != bin) {
                    bin.close();
                }
                if (null != bout) {
                    bout.close();
                }
                if(null != fos) {
                	fos.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalLen;
    }


JAVA File对文件内容的操作:
java IO文件操作

评论