Java 文件处理

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtil {

protected static Logger logger= log4j需要调用

/*
     * 读取指定路径下的文件名
     */
    public static String getFileList(String path, String search) {
        String result = "";
        String os = System.getProperty("os.name");
        File file = new File(path);
        File[] fileList = file.listFiles();
        for (File item : fileList) {
            if (item.exists() && item.isFile()) {
                Integer bo = 1;
                if (!search.equals("")) {
                    if (!item.getName().toUpperCase().contains(search.toUpperCase())) {
                        bo = 0;
                    }
                }
                if (bo == 1) {
                    String cans = "";
                    if (os.toLowerCase().startsWith("win")) {
                        int p = 0;
                        if (item.canRead()) {
                            p += 4;
                        }
                        if (item.canWrite()) {
                            p += 2;
                        }
                        if (item.canExecute()) {
                            p += 1;
                        }
                        cans = p + "" + p + "" + p;
                    } else {
                        try {
                            cans = CmdRunUtil.getRunOneLine("stat -c %a " + item.getCanonicalPath());
                        } catch (IOException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        } catch (InterruptedException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        }
                    }
                    if (item.lastModified() != 0) {
                        if (!result.equals("")) {
                            result += ",";
                        }
                        result += item.getName() + ";" + item.length() + ";" + String.valueOf(item.lastModified()).substring(0, 10) + ";" + cans + ";";
                    }
                }
            }
        }
        return result;
    }

    /*
     * 读取指定路径下的目录名
     */
    public static String getDirectoryList(String path, String search) {
        String result = "";
        String os = System.getProperty("os.name");
        File file = new File(path);
        File[] fileList = file.listFiles();
        for (File item : fileList) {
            if (item.exists() && item.isDirectory()) {
                Integer bo = 1;
                if (!search.equals("")) {
                    if (!item.getName().toUpperCase().contains(search.toUpperCase())) {
                        bo = 0;
                    }
                }
                if (bo == 1) {
                    String cans = "";
                    if (os.toLowerCase().startsWith("win")) {
                        int p = 0;
                        if (item.canRead()) {
                            p += 4;
                        }
                        if (item.canWrite()) {
                            p += 2;
                        }
                        if (item.canExecute()) {
                            p += 1;
                        }
                        cans = p + "" + p + "" + p;
                    } else {
                        try {
                            cans = CmdRunUtil.getRunOneLine("stat -c %a " + item.getPath());
                        } catch (IOException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        } catch (InterruptedException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        }
                    }
                    if (item.lastModified() != 0) {
                        if (!result.equals("")) {
                            result += ",";
                        }
                        result += item.getName() + ";" + item.length() + ";" + String.valueOf(item.lastModified()).substring(0, 10) + ";" + cans + ";";
                    }
                }
            }
        }
        return result;
    }

    /**
     * 根据条件获取文件夹下所有文件以及文件夹
     * 
     * @param path-路径
     * @param search-名称包含
     * @param fileList
     * @return
     */
    public static ArrayList<File> getFileSList(String path, String search, ArrayList<File> fileList) {
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File item : files) {
                if (item.isDirectory()) {
                    if (item.getName().toUpperCase().contains(search.toUpperCase())) {
                        fileList.add(item);
                    }
                    fileList = getFileSList(item.getPath(), search, fileList);
                } else {
                    if (item.getName().toUpperCase().contains(search.toUpperCase())) {
                        fileList.add(item);
                    }
                }
            }
        }
        return fileList;
    }

    /**
     * 根据条件获取文件夹下所有文件以及文件夹
     * 
     * @param path
     * @param search
     * @return
     */
    public static Map<String, Object> getFilesMap(String path, String search) {
        Map<String, Object> map = new HashMap<String, Object>();
        String os = System.getProperty("os.name");
        ArrayList<File> fileList = new ArrayList<File>();
        fileList = getFileSList(path, search, fileList);
        String resultDir = "", resultfile = "";
        for (File file : fileList) {
            if (file.isDirectory()) {
                Integer bo = 1;
                if (!search.equals("")) {
                    if (!file.getName().toUpperCase().contains(search.toUpperCase())) {
                        bo = 0;
                    }
                }
                if (bo == 1) {
                    String cans = "";
                    if (os.toLowerCase().startsWith("win")) {
                        int p = 0;
                        if (file.canRead()) {
                            p += 4;
                        }
                        if (file.canWrite()) {
                            p += 2;
                        }
                        if (file.canExecute()) {
                            p += 1;
                        }
                        cans = p + "" + p + "" + p;
                    } else {
                        try {
                            cans = CmdRunUtil.getRunOneLine("stat -c %a " + file.getPath());
                        } catch (IOException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        } catch (InterruptedException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        }
                    }
                    if (file.lastModified() != 0) {
                        if (!resultDir.equals("")) {
                            resultDir += ",";
                        }
                        resultDir += file.getAbsolutePath().replaceAll("\\\\", "/").replaceFirst(path, "") + ";" + file.length() + ";" + String.valueOf(file.lastModified()).substring(0, 10) + ";" + cans + ";";
                    }
                }
            }
            if (file.isFile()) {
                Integer bo = 1;
                if (!search.equals("")) {
                    if (!file.getName().toUpperCase().contains(search.toUpperCase())) {
                        bo = 0;
                    }
                }
                if (bo == 1) {
                    String cans = "";
                    if (os.toLowerCase().startsWith("win")) {
                        int p = 0;
                        if (file.canRead()) {
                            p += 4;
                        }
                        if (file.canWrite()) {
                            p += 2;
                        }
                        if (file.canExecute()) {
                            p += 1;
                        }
                        cans = p + "" + p + "" + p;
                    } else {
                        try {
                            cans = CmdRunUtil.getRunOneLine("stat -c %a " + file.getCanonicalPath());
                        } catch (IOException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        } catch (InterruptedException e) {
                            cans = "000";
                            logger.error(e.toString(), e);
                        }
                    }
                    if (file.lastModified() != 0) {
                        if (!resultfile.equals("")) {
                            resultfile += ",";
                        }
                        resultfile += file.getAbsolutePath().replaceAll("\\\\", "/").replaceFirst(path, "") + ";" + file.length() + ";" + String.valueOf(file.lastModified()).substring(0, 10) + ";" + cans + ";";
                    }
                }
            }
        }
        map.put("FILES", (resultfile.equals("") ? null : resultfile.split(",")));
        map.put("DIR", (resultDir.equals("") ? null : resultDir.split(",")));
        return map;
    }

    /* 读取指定路径文件或文件名权限 */
    public static String getFileJurisdiction(String path) {
        String os = System.getProperty("os.name");
        File file = new File(path);
        String cans = "";
        if (os.toLowerCase().startsWith("win")) {
            int p = 0;
            if (file.canRead()) {
                p += 4;
            }
            if (file.canWrite()) {
                p += 2;
            }
            if (file.canExecute()) {
                p += 1;
            }
            cans = p + "" + p + "" + p;
        } else {
            try {
                cans = CmdRunUtil.getRunOneLine("stat -c %a " + file.getCanonicalPath());
            } catch (IOException e) {
                cans = "000";
                logger.error(e.toString(), e);
            } catch (InterruptedException e) {
                cans = "000";
                logger.error(e.toString(), e);
            }
        }
        return cans;
    }

    /**
     * 读取文件、文件夹大小
     * 
     * @param fileArr
     * @param size
     * @return
     */
    public static long getSize(File[] fileArr, long size) {
        if (fileArr == null) {
            return size;
        }
        for (File file : fileArr) {
            if (file.isFile()) {
                size += file.length();
            } else if (file.isDirectory()) {
                size = FileUtil.getSize(file.listFiles(), size);
            }
        }
        return size;
    }

    /**
     * 下载远程文件并保存到本地
     * 
     * @param urlStr-远程文件路径
     * @param localPath-本地文件路径
     * @param fileName-文件名
     * @return
     */
    public static boolean downloadFile(String urlStr, String localPath, String fileName) {
        boolean result = false;
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localPath + "/" + fileName);
        try {
            urlfile = new URL(urlStr);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
            result = true;
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                logger.error(e.toString(), e);
            }
        }
        return result;
    }

    /**
     * 创建目录-以及子目录
     * 
     * @param path
     * @return
     */
    public static boolean createDirS(String path) {
        boolean result = false;
        try {
            String[] pathArr = path.split("/");
            StringBuffer tmpPath = new StringBuffer();
            for (int i = 0; i < pathArr.length; i++) {
                tmpPath.append(pathArr[i]).append("/");
                File file = new File(tmpPath.toString());
                if (!file.exists()) {
                    file.mkdir();
                    result = true;
                }
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return result;
    }

    /**
     * 获取回收站中所有文件
     * 
     * @param path-路径
     * @return
     */
    public static Map<String, Object> getRecycleFilesMap(String path) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<FileRecycle> listdirs = new ArrayList<>();
        List<FileRecycle> listfiles = new ArrayList<>();
        File file = new File(path);
        File[] files = file.listFiles();
        for (File item : files) {
            if (item.isDirectory()) {
                // 文件夹
                FileRecycle entity = new FileRecycle();
                entity.setDname(item.getName().replace("_mh_", ":").split("_t_")[0].replaceAll("_bt_", "/"));
                String[] urls = item.getName().split("_bt_");
                String[] nametime = urls[urls.length - 1].split("_t_");
                entity.setName(nametime[0]);
                entity.setRname(item.getName());
                entity.setSize(item.length());
                entity.setTime(Integer.valueOf(nametime[1].split("\\.")[0]));
                listdirs.add(entity);
            } else {
                // 文件
                FileRecycle entity = new FileRecycle();
                entity.setDname(item.getName().replace("_mh_", ":").split("_t_")[0].replaceAll("_bt_", "/"));
                String[] urls = item.getName().split("_bt_");
                String[] nametime = urls[urls.length - 1].split("_t_");
                entity.setName(nametime[0]);
                entity.setRname(item.getName());
                entity.setSize(item.length());
                entity.setTime(Integer.valueOf(nametime[1].split("\\.")[0]));
                listfiles.add(entity);
            }
        }
        map.put("dirs", listdirs);
        map.put("files", listfiles);
        return map;
    }

    /**
     * 删除某个目录及目录下的所有子目录和文件
     * 
     * @param dir
     * @return
     */
    public static boolean deleteDir(File dir) {
        // 如果是文件夹
        if (dir.isDirectory()) {
            // 则读出该文件夹下的的所有文件
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                // File f=new File(String parent ,String child)
                // parent抽象路径名用于表示目录,child 路径名字符串用于表示目录或文件.
                // 连起来刚好是文件路径
                boolean isDelete = deleteDir(new File(dir, children[i]));
                // 如果删完了,没东西删,isDelete==false的时候,则跳出此时递归
                if (!isDelete) {
                    return false;
                }
            }
        }
        // 读到的是一个文件或者是一个空目录,则可以直接删除
        return dir.delete();
    }

    /**
     * 复制某个目录及目录下的所有子目录和文件到新文件夹
     * 
     * @param oldPath-源文件
     * @param newPath-回收站文件
     */
    public static boolean copyFolder(String oldPath, String newPath) {
        try {
            // 读取整个文件夹的内容到file字符串数组,下面设置一个游标i,不停地向下移开始读这个数组
            File fileold = new File(oldPath);// 实际文件位置
            File file = new File(newPath);// 拷贝文件文职
            String filepath = file.getParent();
            (new File(filepath)).mkdirs();
            // 文件直接复制
            if (fileold.isFile()) {
                FileInputStream input = new FileInputStream(fileold);
                // 复制并且改名
                FileOutputStream output = new FileOutputStream(newPath);
                byte[] bufferarray = new byte[1024 * 64];
                int prereadlength;
                while ((prereadlength = input.read(bufferarray)) != -1) {
                    output.write(bufferarray, 0, prereadlength);
                }
                output.flush();
                output.close();
                input.close();
                return true;
            }
            // 目录直接创建目录
            if (fileold.isDirectory()) {
                // 循环目录中所有文件和目录
                for (File item : fileold.listFiles()) {
                    (new File(newPath)).mkdirs();
                    copyFolder(item.getPath(), newPath + "/" + item.getName());
                }
                (new File(newPath)).mkdirs();
            }
            return true;
        } catch (Exception e) {
            logger.error("复制整个文件夹内容操作出错" + e.toString(), e);
        }
        return false;
    }

    /**
     * 清空文件夹
     * 
     * @param dir
     * @return
     */
    public static boolean deleteRecycleDir(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        for (File dir : files) {
            deleteDir(dir);
        }
        return true;
    }

    /**
     * 写入文件
     * 
     * @param path-文件路径
     * @param content-文件内容
     * @param encoding-文件编码
     * @return
     */
    public static boolean write(String path, String content, String encoding) {
        BufferedWriter writer = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            writer = new BufferedWriter(new OutputStreamWriter(fos, encoding));
            writer.write(content);
            writer.flush();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e1) {
                    logger.error(e1.toString(), e1);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    logger.error(e1.toString(), e1);
                }
            }
        }
        return true;
    }

    /**
     * 读取文件
     * 
     * @param path-文件路径
     * @param encoding-文件编码
     * @return
     */
    public static String read(String path, String encoding) {
        String content = "";
        File file = new File(path);
        if (!file.exists()) {
            return content;
        } else {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    content += line + "\n";
                }
            } catch (IOException e) {
                logger.error(e.toString(), e);
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error(e.toString(), e);
                }
            }
        }
        return content;
    }
}

 

public class FileRecycle {
    // 文件完整路径
    private String dname;
    // 文件名称
    private String name;
    // 文件临时名称
    private String rname;
    // 文件大小
    private long size;
    // 文件修改日期
    private Integer time;

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRname() {
        return rname;
    }

    public void setRname(String rname) {
        this.rname = rname;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public Integer getTime() {
        return time;
    }

    public void setTime(Integer time) {
        this.time = time;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值