java.io之文件

来源:互联网 发布:淘宝网的货源哪里找 编辑:程序博客网 时间:2024/06/05 09:05

第0章:简介

第1章:详解

文件工具类FileUtil.java如下:

package com.lsl.util;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Stack;

/**
 * 文件工具类
 * @author <a href="mailto:417877417@qq.com">menergy</a>
 * @version 2013-10-22
 */
public class FileUtil {
    /**
     * 抽象路径名:包括带路径文件和带路径目录
     */
    
    private String path = null;
    private File file = null;
    
    /**
     * 构造器
     *
     * @param path example:/lsl/test
     * @return
     */
    public FileUtil(String path){
        this.path = path;
         init();
    }
    
    /**
     * 构造器
     *
     * @param file 文件或目录
     */
    public FileUtil(File file) {
        this.file = file;
        init();
    }
    
    /**
     * 初始化文件
     */
    private void init() {
        if (file == null) {
            file = new File(path);
        }
    }
    
    /**
     * 实例入口
     *
     * @param path 文件或目录
     * @return
     */
    public synchronized static FileUtil getInstance(String path) {
        return new FileUtil(path);
    }

    /**
     * 实例入口
     *
     * @param file 文件
     * @return
     */
    public synchronized static FileUtil getInstance(File file) {
        return new FileUtil(file);
    }
    
    /**
     * 获取文件实体
     * @return
     */
    public File getFile() {
        return this.file;
    }
    
    /**
     * 与系统有关的路径分隔符,常量
     *
     * @return
     */
    public String getPathSeparator(){
        return file.pathSeparator;
    }
    
    /**
     * 与系统有关的默认名称分隔符,常量
     *
     * @return
     */
    public String getSeparator(){
        return file.separator;
    }
    
    /**
     * 文件或目录是否存在
     *
     * @return
     */
    public boolean exists(){
        return file.exists();
    }
    
    /**
     * 获取文件路径
     * @return
     */
    public String getPath() {
        return file.getPath();
    }
    
    /**
     * 获取文件或目录的名称
     *
     * @return
     */
    public String getName(){
        return file.getName();
    }
    
    /**
     * 获取父目录的路径,如果不存在,返回null
     *
     * @return
     */
    public String getParentPath(){
        return file.getParent();
    }
    
    /**
     * 获取父目录实体,如果不存在,返回null
     *
     * @return
     */
    public File getParentFile(){
        return file.getParentFile();
    }
    
    /**
     * 是否是一个目录
     *
     * @return
     */
    public boolean isDirectory(){
        return file.isDirectory();
    }
    
    /**
     * 文件是否是一个标准文件
     *如果该文件不是一个目录,并且满足其他与系统有关的标准,那么该文件是标准 文件。
     *由 Java 应用程序创建的所有非目录文件一定是标准文件。
     * @return
     */
    public boolean isFile(){
        return file.isFile();
    }
    
    /**
     * 新建文件
     * 当且仅当不存在指定名称的文件时,创建一个新的空文件。
     *
     * @return
     * @throws java.io.IOException
     */
    public File createFile() {
        if (!file.exists()) {
            createParentDir();
            boolean b = false;
            try {
                b = file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (b) {
                return file;
            } else {
                return null;
            }
        } else {
            return file;
        }
    }

    /**
     * 根据初始化的路径,创建父级及以上目录
     *
     * @return
     */
    public File createParentDir() {
        if (!file.exists()) {
            Stack<File> stack = new Stack<File>();
            File current = file.getParentFile();
            // 把缺失的目录放到栈里
            while (current != null && !current.exists()) {
                stack.push(current);
                current = current.getParentFile();
            }
            // 建立缺失的目录
            while (!stack.isEmpty()) {
                stack.pop().mkdir();
            }
        }
        return file;
    }

    /**
     * 删除文件
     *
     * @return
     */
    public boolean deleteFile(){
        return file.delete();
    }
    
    /**
     * 新建目录(不包括父目录)
     * 如果父目录不存在,则无法新建
     *
     * @return
     */
    public boolean createDir(){
        return file.mkdir();
    }
    
    /**
     * 新建目录(包括父目录)
     * 包括所有必需但不存在的父目录
     *
     * @return
     */
    public boolean createDirs(){
        return file.mkdirs();
    }
    
    /**
     * 删除目录
     *
     * @return
     */
    public boolean deleteDir() {
        return deleteDir(this.file);
    }

    /**
     * 删除指定文件目录
     *
     * @param dir 文件目录
     * @return
     */
    public boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
    
    /**
     * 在虚拟机终止时,请求删除此抽象路径名表示的文件或目录
     */
    public void deleteOnExit(){
        file.deleteOnExit();
    }
    
    /**
     * 在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。
     *
     * @param prefix - 用于生成文件名的前缀字符串;必须至少是三字符长
     * @param suffix - 用于生成文件名的后缀字符串;可以为 null,在这种情况下,将使用后缀 ".tmp"
     * @param directory - 将创建的文件所在的目录;如果使用默认临时文件目录,则该参数为 null
     * @return 表示新建空文件的抽象路径名
     */
    public File createTempFile(String prefix, String suffix, File directory){
        try {
                return file.createTempFile(prefix, suffix, directory);
        } catch (IllegalArgumentException iae) {
            System.out.println("prefix 参数至少包含三个字符!");
        } catch (IOException ioe){
            System.out.println("无法创建文件!");
        }
        return null;
    }
    
    /**
     * 文件或目录重命名,只能重命名名字,不能移动
     *
     * @param otherName 重命名的文件名
     * @return
     */
    public boolean renameFileOrDir(String otherName) {
        String otherPath = null;
        File otherFile = null;

        otherPath = file.getParent() + "/" + otherName;

        otherFile = new File(otherPath);

        if (file.exists()) {
            if (file.renameTo(otherFile)) {
                return true;
            }
        }

        return false;
    }
    
    
    /**
     * 文件移动并重命名(包括路径和文件名)
     * 如果存在新文件相同的文件,重命名失败;如果路径不同,将移动原来的文件到目标路径
     *
     * @param dest
     * @return
     */
    public boolean renameFileTo(String destFilePath){
        File dest = new File(destFilePath);
        if(dest != null && !dest.exists()){
            return file.renameTo(dest);
        }else{
            return false;
        }
    }
    
    /**
     * 移动文件或目录,文件名不变
     *
     * @param destPath
     */
    public boolean moveFile(String destPath) {
        File destFile = null;

        destFile = new File(destPath + file.getName());
        if (file.exists()) {
            if (file.renameTo(destFile)) {
                return true;
            }
        }
        return false;
    }
   
    /**
     * 获取抽象路径名的规范形式
     *
     * @return
     */
    public File getCanonicalFile(){
        try {
            return file.getCanonicalFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取抽象路径名的的规范路径
     *
     * @return
     */
    public String  getCanonicalPath(){
        try {
            return file.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取抽象路径名所在分区的总容量大小
     *
     * @return
     */
    public long getTotalSpace(){
        return file.getTotalSpace();
    }
    
    /**
     * 获取抽象路径名所在分区中未分配的字节数
     *
     * @return
     */
    public long getFreeSpace(){
        return file.getFreeSpace();
    }
    
    /**
     * 获取抽象路径名所在分区的可用于此虚拟机的字节数
     *
     * @return
     */
    public long getUsableSpace(){
        return file.getUsableSpace();
    }
    
    /**
     * 抽象路径名是否为绝对路径名
     *
     * @return
     */
    public boolean isAbsolute(){
        return file.isAbsolute();
    }
    
    /**
     * 文件是否是一个隐藏文件
     *
     * @return
     */
    public boolean isHidden(){
        return file.isHidden();
    }
    
    /**
     * 抽象路径名表示的文件的长度(字节数,包括换行等)
     *
     * @return
     */
    public long length(){
        return file.length();
    }
    
    /**
     * 获取目录下的所有文件和目录名称(不带路径),初始化时必须指定的是目录路径
     *
     * @return
     */
    public String[] getAllList(){
        String[] value = null;
        if(file.exists()){
            value = file.list();
            //根据文件名进行排序
            Arrays.sort(value);
        }
        return value;
    }
    
    /**
     * 目录中满足指定过滤器的文件和目录名称(不带路径),初始化时必须指定的是目录路径
     *
     * @param fileName
     * @param extendName
     * @param type 0或null:不限制;1:目录;2:文件
     * @return
     */
    public String[] getList(String fileName, String extendName, Integer type){
        String[] value = null;
        DefualtFilenameFilter filter = null;
        filter = new DefualtFilenameFilter(fileName, extendName, type);
        value = file.list(filter);
        //根据文件名进行排序
        if (value != null) {
            Arrays.sort(value);
        }
        return value;
    }
    
    /**
     * 获取目录下的所有文件(包括目录,带路径),初始化时必须指定的是目录路径
     *
     * @return
     * @throws java.io.IOException
     */
    public File[] getAllFiles() {
        File[] value = null;
        if (file.exists()) {
            value = file.listFiles();
            //根据文件名进行排序
            Arrays.sort(value);
        }
        return value;
    }
    
    /**
     * 获取目录下的所有经过过滤器的文件(不包括目录,带路径),初始化时必须指定的是目录路径
     *
     * @param fileName   指定的文件名,模糊匹配,没有指定可以用null或""代替
     * @param extendName 指定的扩展名,模糊匹配,没有指定可以用null或""代替
     * @return
     */
    public File[] getFiles(String fileName, String extendName) {
        File[] files = null;
        DefualtFileFilter filter = null;
        filter = new DefualtFileFilter(fileName, extendName);
        files = file.listFiles(filter);
        //根据文件名进行排序
        if (files != null) {
            Arrays.sort(files);
        }
        return files;
    }
    
    /**
     * 获取目录下的所有经过过滤器的文件(包括目录,带路径),初始化时必须指定的是目录路径
     *
     * @param fileName   指定的文件名,模糊匹配,没有指定可以用null或""代替
     * @param extendName 指定的扩展名,模糊匹配,没有指定可以用null或""代替
     * @param type 0或null:不限制;1:目录;2:文件
     * @return
     */
    public File[] getFiles(String fileName, String extendName, Integer type){
        File[] files = null;
        DefualtFilenameFilter filter = null;
        filter = new DefualtFilenameFilter(fileName, extendName, type);
        files = file.listFiles(filter);
        //根据文件名进行排序
        if (files != null) {
            Arrays.sort(files);
        }
        return files;
    }
    
    /**
     * 可用的文件系统根
     *
     * @return example: D:\
     */
    public File[] getListRoots(){
        return file.listRoots();
    }
    
    /**
     * 文件是否可执行
     *
     * @return
     */
    public boolean canExecute(){
        return file.canExecute();
    }
    
    /**
     * 文件是否可读取
     *
     * @return
     */
    public boolean canRead(){
        return file.canRead();
    }
    
    /**
     * 文件是否可修改
     *
     * @return
     */
    public boolean canWrite(){
        return file.canWrite();
    }
    
    /**
     * 设置此抽象路径名所有者执行权限
     *
     * @param executable
     * @return
     */
    public boolean setExecutable(boolean executable){
        return file.setExecutable(executable);
    }
    
    /**
     * 设置此抽象路径名的所有者或所有用户的执行权限
     *
     * @param executable 如果为 true,则设置允许执行操作的访问权限;如果为 false,则不允许执行操作。
     * @param ownerOnly 如果为 true,则执行权限只适用于所有者的执行权限;否则适用于所有用户。
     * @return
     */
    public boolean setExecutable(boolean executable, boolean ownerOnly){
        return file.setExecutable(executable, ownerOnly);
    }
    
    /**
     * 设置此抽象路径名所有者读权限
     *
     * @param readable
     * @return
     */
    public boolean setReadable(boolean readable){
        return file.setReadable(readable);
    }
    
    /**
     * 设置此抽象路径名的所有者或所有用户的读权限
     *
     * @param readable
     * @param ownerOnly
     * @return
     */
    public boolean setReadable(boolean readable, boolean ownerOnly){
        return file.setReadable(readable, ownerOnly);
    }

    /**
     * 标记此抽象路径名指定的文件或目录,从而只能对其进行读操作
     *
     * @return
     */
    public boolean setReadOnly(){
        return file.setReadOnly();
    }
    
    /**
     * 设置此抽象路径名所有者写权限
     *
     * @param writable
     * @return
     */
    public boolean setWritable(boolean writable){
        return file.setWritable(writable);
    }
    
    /**
     * 设置此抽象路径名的所有者或所有用户的写权限
     *
     * @param writable
     * @param ownerOnly
     * @return
     */
    public boolean setWritable(boolean writable, boolean ownerOnly){
        return file.setWritable(writable, ownerOnly);
    }
    
    /**
     * 抽象路径名表示的文件最后一次被修改的时间
     *
     * @return
     */
    public long getLastModified(){
        return file.lastModified();
    }
    
    /**
     * 设置此抽象路径名指定的文件或目录的最后一次修改时间
     *
     * @param time
     * @return
     */
    public boolean setLastModified(long time){
        return file.setLastModified(time);
    }
    
    /**
     * 构造一个表示此抽象路径名的 file: URI
     * 如果要转成URL,可以首先通过 toURI 方法将其转换为 URI,然后通过 URI.toURL 方法将 URI 装换为 URL
     *
     * @return example: file:/E:/data2/data3/123.txt
     */
    public URI toURI(){
        return file.toURI();
    }
    
    /**
     * 将此抽象路径名转换为一个 file: URL
     *
     * @return example: file:/E:/data2/
     */
    public URL toURL(){
        try {
            return file.toURI().toURL();
        } catch (MalformedURLException e) {
            throw new RuntimeException("Unexpected exception on file [" + file + "]", e);
        }
    }
    
    /**
     * 按字母顺序比较两个抽象路径名
     * 在 UNIX 系统上,比较路径名时,字母大小写通常很重要,而在 Microsoft Windows 系统上,这通常不重要。
     * 如果该参数等于此抽象路径名,则返回零;如果此抽象路径名在字母顺序上小于该参数,则返回小于零的值;
     * 如果此抽象路径名在字母顺序上大于该参数,则返回大于零的值
     * @param pathname
     * @return
     */
    public int compareTo(File pathname){
        return file.compareTo(pathname);
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        FileUtil fileUtil = FileUtil.getInstance("E://data2");
        System.out.println("是否可执行:" + fileUtil.getFile().exists());
        System.out.println(fileUtil.toURL());
        System.out.println(fileUtil.exists());
        System.out.println(fileUtil.toURI());
        System.out.println(fileUtil.deleteDir());

    }
}

/**
 * 文件过滤器
 *
 * @author <a href="mailto:417877417@qq.com">menergy</a>
 * @version 2013-10-22
 */
class DefualtFileFilter implements FileFilter {

    private String fileName = null;
    private String extendName = null;

    /**
     * 构造函数
     *
     * @param fileName
     * @param extendName
     */
    public DefualtFileFilter(String fileName, String extendName) {
        this.fileName = fileName;
        this.extendName = extendName;
    }

    /**
     * @param file
     * @return
     */
    @Override
    public boolean accept(File file) {
        String allName = null;
        String[] names = null;
        String inName = "";
        String extName = "";
        boolean nameCheck = false;
        boolean extCheck = false;

        if (file.isFile()) {
            allName = file.getName();
            names = allName.split("\\.", -1);

            if (names.length == 1) {
                inName = names[0];
            } else {
                for (int i = 0; i < names.length - 1; i++) {
                    inName = inName + names[i];
                }

                extName = names[names.length - 1];
            }
            //过滤文件名
            if (fileName != null) {
                if (!fileName.equals("")) {
                    if (inName.indexOf(fileName) >= 0) {
                        nameCheck = true;
                    }
                } else {
                    nameCheck = true;
                }
            } else {
                nameCheck = true;
            }
            //过滤扩展名
            if (extendName != null) {
                if (!extendName.equals("")) {
                    if (extName.indexOf(extendName) >= 0) {
                        extCheck = true;
                    }
                } else {
                    extCheck = true;
                }
            } else {
                extCheck = true;
            }
        }

        return nameCheck && extCheck;
    }
}

/**
 *  文件名过滤器
 *
 * @author <a href="mailto:417877417@qq.com">menergy</a>
 * @version 2013-10-22
 */
class DefualtFilenameFilter implements FilenameFilter{

    private String fileName = null;
    private String extendName = null;
    private Integer type = null;
    
    /**
     * 构造函数
     *
     * @param fileName
     * @param extendName
     * @param type 0或null:不限制;1:目录;2:文件
     */
    public DefualtFilenameFilter(String fileName, String extendName,Integer type) {
        this.fileName = fileName;
        this.extendName = extendName;
        this.type = type;
    }
    /*
     *
     */
    @Override
    public boolean accept(File dir, String name) {
        String[] names = null;
        String inName = "";
        String extName = "";
        boolean nameCheck = false;
        boolean extCheck = false;
        boolean typeCheck = false;
        
        names = name.split("\\.", -1);
        if (names.length == 1) {
            inName = names[0];
        } else {
            for (int i = 0; i < names.length - 1; i++) {
                inName = inName + names[i];
            }

            extName = names[names.length - 1];
        }
        //过滤文件名
        if (fileName != null) {
            if (!fileName.equals("")) {
                if (inName.indexOf(fileName) >= 0) {
                    nameCheck = true;
                }
            } else {
                nameCheck = true;
            }
        } else {
            nameCheck = true;
        }
        //过滤扩展名
        if (extendName != null) {
            if (!extendName.equals("")) {
                if (extName.indexOf(extendName) >= 0) {
                    extCheck = true;
                }
            } else {
                extCheck = true;
            }
        } else {
            extCheck = true;
        }
        
        //过滤类型
        if(type != null && (type == 1 || type == 2)){
            File actualFile = new File(dir,name);
            if(actualFile != null){
                if((type == 1 && actualFile.isDirectory()) || (type == 2 && !actualFile.isDirectory())){
                    typeCheck = true;
                }else{
                    typeCheck = false;
                }
            }
        }else{
            typeCheck = true;
        }

        return nameCheck && extCheck && typeCheck;
    }
    

}


原创粉丝点击