FileUtils文件操作

/**
 * <p>Title: 关于文件操作的通用方法 </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2014</p>
 * @Team: 技术1部Java开发小组
 * @Author Andy-ZhichengYuan
 * @Date 2014年12月12日
 * @Version V1.0    */
public class FileUtils {
    private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);
    public static final String FILEDOT = ".";
    public static final String FILEBAR = "\\";
    public static final String REFILEBAR = "/";
    public static final String TXTEXT = ".txt";
    public static final String XLSEXT = ".xls";

    /** 去掉文件名的后缀	 */
    public static String getFileNameWithoutPostfix(String filename) {
        return StringUtils.substringBeforeLast(filename, ".");
    }

    /** 为文件路径创建各级目录 */
    public static void createFolderForFile(String filePath) {
        String folderPath = getFolderPath(filePath);
        File file = new File(folderPath);
        file.mkdirs();
        file = null;
    }

    /** 获取路径的最小级目录	 */
    public static String getFolderPath(String filePath) {
        if (StringTools.isTrimNull(filePath))
            return null;
        filePath = StringUtils.replace(filePath, "/", "\\");
        return StringUtils.substringBeforeLast(filePath, "\\");
    }

    /** 合并目录,去掉多余的/或者\  */
    public static String mergePath(String path, String subPath) {
        if (StringTools.isTrimNull(path))
            return subPath;
        if (StringTools.isTrimNull(subPath))
            return path;
        if (StringUtils.endsWith(path, "/") || StringUtils.endsWith(path, "\\"))
            path = StringUtils.substring(path, 0, path.length() - 1);
        if (!StringUtils.startsWith(subPath, "/")
                && !StringUtils.startsWith(subPath, "\\")) {
            if (StringUtils.startsWith(path, "/"))// contains
                subPath = "/" + subPath; // 存储网关
            else
                subPath = "\\" + subPath; // Win平台
        }
        return path + subPath;
    }

    /** 合并<N级>目录,去掉多余的'/' 或者 '\'
     * @param subPath : sub1, sub2, sub3... 或 String[] subs   */
    public static String mergePath(String dir, String... subPath) {
        if (subPath != null && subPath.length != 0) {
            if (subPath.length == 1) {
                return mergePath(dir, subPath[0]);
            } else {
                String temp = subPath[0];
                for (int i = 1; i < subPath.length; i++) {
                    temp = mergePath(temp, subPath[i]);
                }
                return mergePath(dir, temp);
            }
        } else {
            return dir;
        }
    }

    /** 拷贝文件	 */
    public static void copy(String from, String to)
            throws FileNotFoundException, IOException {
        copy(new File(from), new File(to));
    }

    /** 拷贝文件     */
    public static void copy(File from, File to)
            throws FileNotFoundException, IOException {
        try (FileOutputStream outStream = new FileOutputStream(to);
                FileInputStream inputStream = new FileInputStream(from);
                FileChannel outChannel = outStream.getChannel();
                FileChannel inChannel = inputStream.getChannel();) {
            outChannel.transferFrom(inChannel, 0, inChannel.size());
            outStream.flush();
        }
    }

    /** 复制文件     */
    public static void copyFile(String sourcePath, String destPath)
            throws IOException {
        if (!isExists(sourcePath)) {
            LOG.warn("系统未找到源文件:" + sourcePath);
            return;
        } else if (destPath == null || !isFilePath(destPath)) {
            LOG.warn("复制文件目标路径非法:" + destPath);
            return;
        } else {
            try (FileInputStream srcStream = new FileInputStream(
                    new File(sourcePath));
                    FileChannel srcChannel = srcStream.getChannel()) {
                String destDir = getLastDIR(destPath);
                File folder = new File(destDir);
                if (!folder.exists())// 不存在目标目录,则创建
                    folder.mkdirs();
                try (FileOutputStream destStream = new FileOutputStream(
                        new File(destPath));
                        FileChannel destChannel = destStream.getChannel()) {
                    destChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    destStream.flush();
                }
            }
        }
    }

    /** 删除文件夹【目录】下,指定的文件	 */
    public static void delete(String dir, FileFilter filter) {
        if (isDir(dir)) {
            String path = null;
            Set<String> set = getFilePath(dir, filter);
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                path = it.next();
                delete(path);
                path = null;
            }
            set.clear();
            set = null;
        }
    }

    /** 删除文件	 */
    public static void delete(String path) {
        if (!StringTools.isTrimNull(path)) {
            delete(new File(path));
        }
    }

    /** 删除文件或文件夹	 */
    public static void delete(File file) {
        if (file == null || !file.exists())
            return;
        if (file.isFile())
            file.delete();
        else if (file.isDirectory()) {
            File[] subFiles = file.listFiles();
            if (subFiles != null) {
                for (File subFile : subFiles) {
                    delete(subFile);
                }
            }
            file.delete();
        }
    }

    /** 文件重命名 */
    public static void reNamed(String oldFile, String newFile) {
        if (!StringTools.isTrimNull(oldFile, newFile)) {
            String oldName = getFileName(oldFile, true);
            String newName = getFileName(newFile, true);
            if (!StringUtils.equalsIgnoreCase(oldName, newName)) {
                delete(newFile);// 先删除重命名之前的文件
                File old = new File(oldFile);
                if (old.exists()) {
                    old.renameTo(new File(newFile));
                }
                old = null;
            }
            oldName = null;
            newName = null;
        }
    }

    /** 是否是合法的文件目录:<br>
     * 1. 包含 “\\” 或 “/”    <br>
     * 2. 结束符为 “\\” 或 “/”   */
    public static boolean isDirFile(String url) {
        if (url != null) {
            boolean b1 = StringUtils.contains(url, FILEBAR);
            boolean b2 = StringUtils.contains(url, REFILEBAR);
            if (b1 || b2) {
                b1 = StringUtils.endsWith(url, FILEBAR);
                b2 = StringUtils.endsWith(url, REFILEBAR);
                return (b1 || b2);
            }
        }
        return false;
    }

    /** 是否是合法的文件目录: <br>
     * 1. 包含 “\\” 或 “/”     <br>
     * 2. 结束符为 “\\” 或 “/”  <br>
     * 3. 最后5个字符中不包含 “<b>.</b>”   */
    public static boolean isFileDIR(String dir) {
        boolean flag = false;
        if (dir != null) {
            boolean b1 = StringUtils.contains(dir, FILEBAR);
            boolean b2 = StringUtils.contains(dir, REFILEBAR);
            if (b1 || b2) {
                b1 = StringUtils.endsWith(dir, FILEBAR);
                b2 = StringUtils.endsWith(dir, REFILEBAR);
                if (b1 || b2)
                    flag = true;
                else {
                    if (dir.length() > 5) {// 最后5个字符中不能包含'.'
                        b1 = StringUtils.substring(dir, dir.length() - 5)
                                .contains(FILEDOT);
                        if (!b1)
                            flag = true;
                    }
                }
            }
        }
        return flag;
    }

    /** 是否是合法的文件路径:<br>
     * 1. 包含 “\\” 或 “/”  <br>
     * 2. 结束符不为 “\\” 和 “/” <br>
     * 3. 最后5个字符中必包含 “<b>.</b>”   */
    public static boolean isFilePath(String path) {
        boolean flag = false;
        if (path != null) {
            boolean b1 = StringUtils.contains(path, FILEBAR);
            boolean b2 = StringUtils.contains(path, REFILEBAR);
            if (b1 || b2) {
                b1 = StringUtils.endsWith(path, FILEBAR);
                b2 = StringUtils.endsWith(path, REFILEBAR);
                if (!b1 && !b2) {
                    if (path.length() > 5) {// 最后5个字符中包含'.'
                        flag = StringUtils.substring(path, path.length() - 5)
                                .contains(FILEDOT);
                    }
                }
            }
        }
        return flag;
    }

    /** 是否是合法的UNIX文件目录   */
    public static boolean isUnixDir(String dir) {
        boolean flag = false;
        if (dir != null && dir.length() > 2) {
            if (dir.startsWith(FILEBAR) || dir.startsWith(REFILEBAR)) {
                if (dir.endsWith(FILEBAR) || dir.endsWith(REFILEBAR)) {
                    flag = true;
                } else {
                    if (!dir.substring(dir.length() - 4).contains(FILEDOT))
                        flag = true;
                }
            }
        }
        return flag;
    }

    /** 是否是合法的<中级>文件目录   */
    public static boolean isMidDir(String dir) {
        boolean flag = false;
        if (dir != null && dir.length() > 2) {
            if (dir.endsWith(FILEBAR) || dir.endsWith(REFILEBAR)) {
                flag = true;
            } else {
                if (!dir.substring(dir.length() - 4).contains(FILEDOT))
                    flag = true;
            }
        }
        return flag;
    }

    /** 是否是合法的文件目录   */
    public static boolean isDir(String dir, boolean isWin) {
        boolean flag = false;
        if (dir != null && dir.length() > 2) {
            if (isWin && dir.contains(":")) {
                if (dir.indexOf(":") == 1) {
                    flag = isMidDir(dir);
                }
            } else {
                flag = isUnixDir(dir);
            }
        }
        return flag;
    }

    /** 是否是合法的文件目录:<br>
     * 1. 包含 “\\” 或 “/”  <br>
     * 2. 结束符为 “\\” 或 “/” <br>
     * 3. 最后5个字符中不包含 “<b>.</b>”   */
    public static boolean isDir(String dir) {
        boolean flag = false;
        if (dir != null && dir.length() > 5) {
            // dir.contains(":")
            boolean b1 = StringUtils.contains(dir, FILEBAR);
            boolean b2 = StringUtils.contains(dir, REFILEBAR);
            if (b1 || b2) {
                b1 = StringUtils.endsWith(dir, FILEBAR);
                b2 = StringUtils.endsWith(dir, REFILEBAR);
                if (b1 || b2)
                    flag = true;
                else {
                    b1 = StringUtils.substring(dir, dir.length() - 5)
                            .contains(FILEDOT);
                    if (!b1)
                        flag = true;
                }
            }
        }
        return flag;
    }

    /** 是否是合法的文件目录【结尾】:<br>
     * 1. 包含 “\\” 或 “/”    <br>
     * 2. 结束符为 “\\” 或 “/”   */
    public static boolean isDirEnd(String dir) {
        boolean flag = false;
        if (dir != null && dir.length() > 5) {
            // dir.contains(":")
            dir = StringUtils.replace(dir, REFILEBAR, FILEBAR);
            flag = StringUtils.endsWith(dir, FILEBAR);
        }
        return flag;
    }

    /** 是否是合法的文件目录:<br>
     * 1. 包含 “\\” 或 “/”  <br>
     * 2. 结束符为 “\\” 或 “/” <br>  */
    public static boolean isDir2(String dir) {
        boolean flag = false;
        if (dir != null && dir.length() > 5) {
            dir = StringUtils.replace(dir, REFILEBAR, FILEBAR);
            if (StringUtils.endsWith(dir, FILEBAR)) {
                flag = true;
            } else {
                String name = StringUtils.substringAfterLast(dir, FILEBAR);
                flag = !StringUtils.contains(name, FILEDOT);
                name = null;
                if (!flag) {
                    flag = (new File(dir).isDirectory());
                }
            }
        }
        return flag;
    }

    /** 检查文件的后缀类型是否预期一致
     * @param ext : .Zip 、.txt 、.log 、.xls ... */
    public static boolean isSomeExt(String fileName, String ext) {
        boolean flag = true;
        if (fileName == null || ext == null || !fileName.contains(FILEDOT)) {// ||
            // !file.contains(fileBar)
            flag = false;
        } else {
            String type = fileName.substring(fileName.lastIndexOf(FILEDOT));
            if (!StringUtils.equalsIgnoreCase(ext, type))
                flag = false;
        }
        return flag;
    }

    /** File路径下的文件是否存在 */
    public static boolean isExists(String file) {
        boolean flag = true;
        if (StringUtils.isEmpty(file)) {
            flag = false;
        } else if (isFilePath(file)) {// 符合文件路径
            File f = new File(file);
            flag = isExists(f);
            f = null;
        } else {
            flag = false;
        }

        return flag;
    }

    /** DIR目录是否存在 */
    public static boolean isDirExists(String dir) {
        boolean flag = true;
        if (dir == null || "".equals(dir.trim())) {
            flag = false;
        } else {
            if (isDir(dir)) {// 符合文件路径
                File f = new File(dir);
                flag = isExists(f);
                f = null;
            } else {
                flag = false;
            }
        }
        return flag;
    }

    /** File<文件>或<目录>是否存在 */
    public static boolean isExists(File file) {
        if (file == null) {
            return false;
        } else {
            return file.exists();
        }
    }

    /** 创建DIR 文件夹目录结构 */
    public static void createDIR(String dir) {
        if (isDir(dir)) {
            File folderFile = new File(dir);
            if (!folderFile.exists()) {
                folderFile.mkdirs();
                folderFile = null;
            }
        }
    }

    /** 创建File路径下的文件 */
    public static void createFile(String file) {
        try {
            if (file != null && !isExists(file)) {
                createLastDIR(file);// 先创建目录
                File f = new File(file);
                f.createNewFile();
                f = null;
            }
        } catch (IOException e) {
            LOG.error("文件创建出错:" + file, e);
        }
    }

    /** 创建File路径下的文件 */
    public static void createFile(File file) {
        try {
            if (file != null && !isExists(file)) {
                // createFolderForFile(file.getAbsolutePath());
                createLastDIR(file.getPath());
                file.createNewFile();
            }
        } catch (IOException e) {
            LOG.error("文件创建出错:", e);
        }
    }

    public static BufferedReader getBuffReader(String file, String ext) {
        try {
            if (isExists(file) && isSomeExt(file, ext)) {
                return new BufferedReader(new FileReader(new File(file)));
            }
        } catch (FileNotFoundException e) {
            LOG.error("文件未找到:", e);
        }
        return null;
    }

    /** 根据文件路径file来获取它的<最终>文件<目录> */
    public static String getLastDIR(String file) {
        String lastDir = null;
        if (isFilePath(file)) {
            file = StringUtils.replace(file, "/", "\\");
            lastDir = StringUtils.substringBeforeLast(file, "\\") + "\\";
            // int last = file.lastIndexOf("\\");
            // if (last > 0) lastDir = StringUtils.substring(file, 0, last + 1);
        }
        return lastDir;
    }

    

    /** 获取DIR目录下以start开始,后缀名为EXT的<文件名称>列表 */
    public static Set<String> getFileSet(String dir, String start, String ext) {
        return getFileSet(dir, start, null, ext);
    }

    /** 获取DIR目录下以start开始,后缀名为EXT的<文件名称>列表 */
    public static Set<String> getFileSet(String dir, String start, String midd,
            String ext) {
        FileFilter filter = new FileFilter(start, midd, ext);
        return getFileSet(dir, filter);
    }

    /** 获取DIR目录下以  filter<过滤器> 过滤  的<文件名称>列表 */
    public static Set<String> getFileSet(String dir, FileFilter filter) {
        // Set<String> fileSet = new HashSet<String>();
        SortedSet<String> fileSet = new TreeSet<String>();
        if (dir != null && !"".equals(dir)) {
            File folder = new File(dir);
            if (folder.exists() && folder.isDirectory()) {
                String[] list = null;
                if (filter != null) {
                    list = folder.list(filter);
                } else
                    list = folder.list();
                if (list == null)
                    return fileSet;

                for (int i = 0; i < list.length; i++) {
                    fileSet.add(list[i]);
                }
                list = null;
                folder = null;
            }
        }
        return fileSet;
    }

    /** 获取DIR目录下以  filter<过滤器> 过滤 <未排序> 的<文件名称>列表 */
    public static List<String> getFileList(String dir, FileFilter filter) {
        List<String> fileSet = new ArrayList<String>();
        if (dir != null && !"".equals(dir)) {
            File folder = new File(dir);
            if (folder.exists() && folder.isDirectory()) {
                String[] list = null;
                if (filter != null)
                    list = folder.list(filter);
                else
                    list = folder.list();
                if (list == null)
                    return fileSet;

                for (int i = 0; i < list.length; i++) {
                    fileSet.add(list[i]);
                }
                list = null;
                folder = null;
            }
        }
        return fileSet;
    }

    /** 获取<DIR目录>下以 filter<过滤器> 过滤  的所有文件的<全路径>列表
     * @return Set<文件全路径> */
    public static Set<String> getFilePath(String dir, FileFilter filter) {
        Set<String> fileSet = new TreeSet<String>();
        if (isDir(dir)) {
            File folder = new File(dir);
            // folder.exists() && folder.isDirectory()

            String path = null;
            String[] list = null;
            if (filter != null)
                list = folder.list(filter);
            else
                list = folder.list();
            if (list == null)
                return fileSet;

            for (int i = 0; i < list.length; i++) {
                path = mergePath(dir, list[i]);
                if (isFilePath(path)) // new File(path).isFile()
                    fileSet.add(path);
                path = null;
            }
            list = null;
            folder = null;
        }
        return fileSet;
    }

    /** 获取当前<dir>目录以下<所有子目录> 的<全路径>列表
     * @care:不包括当前<dir>目录在内
     * @return Set<目录全路径> */
    public static Set<String> getDirs(String dir) {
        Set<String> dirSet = new TreeSet<String>();
        if (isDir(dir)) {
            File folder = new File(dir);
            String[] list = folder.list();
            if (list == null)
                return dirSet;

            File f = null;
            String path = null;
            for (String s : list) {
                path = mergePath(dir, s);
                f = new File(path);
                if (f.isDirectory()) {
                    // 保存目录路径
                    dirSet.add(path);
                    // 递归调用,获取目录下的子目录
                    dirSet.addAll(getDirs(path));
                }
                f = null;
                path = null;
            }
            list = null;
            folder = null;
        }
        return dirSet;
    }

    /** 获取<DIR目录>以及<所有子目录>下以  filter<过滤器> 过滤  的所有文件的<全路径>列表
     * @return Set<文件全路径> */
    public static Set<String> getFilePaths(String dir, FileFilter filter) {
        Set<String> fileSet = new TreeSet<String>();
        if (isDir(dir)) {
            Set<String> dirSet = getDirs(dir);
            dirSet.add(dir);

            File folder = null;
            String path = null;
            String[] list = null;
            Iterator<String> itr = dirSet.iterator();
            while (itr.hasNext()) {
                path = itr.next();
                folder = new File(path);
                if (filter != null) {// 文件名过滤
                    list = folder.list(filter);
                    if (list != null) {
                        for (String s : list) {
                            fileSet.add(mergePath(path, s));
                        }
                    }
                } else {
                    String url = null;
                    list = folder.list();
                    if (list != null) {
                        for (String s : list) {
                            url = mergePath(path, s);
                            if (isFilePath(url)) {// new File(path).isFile()
                                fileSet.add(url);
                            } else {// new File(path).isDirectory()
                                url = null;
                                continue;// 目录不作处理
                            }
                            url = null;
                        }
                    }
                    url = null;
                }
                list = null;
                path = null;
                folder = null;
            }
        }
        return fileSet;
    }

    

    /** 根据文件路径,获取文件的( .后缀名 ) */
    public static String getFileExt(String filePath) {
        if (isFilePath(filePath)) {
            return "." + StringUtils.substringAfterLast(filePath, FILEDOT);
        }
        return null;
    }

    /** 根据文件路径,获取最终文件的名称(不带后缀名) */
    public static String getFileName(String filePath) {
        String name = null;
        if (isFilePath(filePath)) {
            // 算法1:通过File处理
            File file = new File(filePath);
            int last = file.getName().lastIndexOf(FILEDOT);
            if (last <= 0)
                name = file.getName();
            else
                name = file.getName().substring(0, last);
            file = null;

            // 算法2:纯字符串处理
            if (name == null || "".equals(name.trim())) {
                int last1 = filePath.lastIndexOf(FILEBAR);
                int last2 = filePath.lastIndexOf(REFILEBAR);
                last = (last1 < last2) ? last2 : last1;
                last1 = filePath.lastIndexOf(FILEDOT);
                if (last > 0 && last1 > last)
                    name = filePath.substring(last + 1, last1);
            }
        }
        return name;
    }

    /** 根据文件路径,获取最终文件的名称
     * @param filePath: 文件路径
     * @param isHasExt: 是否包含文件的扩展名   */
    public static String getFileName(String filePath, boolean isHasExt) {
        String name = null;
        if (filePath != null) {
            filePath = StringUtils.replace(filePath, REFILEBAR, FILEBAR);
            // int last = StringUtils.lastIndexOf(filePath, fileBar);
            // if(last >= 0){ }
            if (isHasExt)
                // name = filePath.substring(last + 1);
                name = StringUtils.substringAfterLast(filePath, FILEBAR);
            else {
                // name = filePath.substring(last + 1,
                // filePath.lastIndexOf(fileDot));
                name = StringUtils.substringAfterLast(filePath, FILEBAR);
                name = StringUtils.substringBeforeLast(name, FILEDOT);
            }
        }
        return name;
    }

    /** 根据文件路径,获取最终文件的全名称(带后缀名) */
    public static String getFullFName(String filePath) {
        String name = null;
        if (filePath != null) {
            // int last = filePath.lastIndexOf(fileBar);
            // if (last <= 0) last = filePath.lastIndexOf(reFileBar);
            // name = filePath.substring(last + 1, filePath.length());

            filePath = StringUtils.replace(filePath, "/", "\\");
            name = StringUtils.substringAfterLast(filePath, "\\");
        }
        return name;
    }

    /**
     * 保存文件
     * @param msgArray         需要保存的内容
     * @param filePath         需要保存的绝对路径
     * @param isAppend         是否追加文件,true:是,false:否	 */
    public static void writeFile1(String content, String outFile,
            boolean isAppend) {
        BufferedWriter writer = null;
        try {
            if (!isAppend) {// 如果是不追加内容,覆盖文件,则先清空该文件
                File f = new File(outFile);
                if (f.exists()) {
                    FileOutputStream out = new FileOutputStream(outFile, false);
                    out.close();
                }
            }
            createLastDIR(outFile);
            writer = new BufferedWriter(new FileWriter(outFile, isAppend));

            writer.write(content);
            writer.flush();
        } catch (Exception e) {
            LOG.error("IO出错:", e);
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                LOG.error("IO出错:", e);
            }
        }
    }

    /**
     * 将组织好的<Text文件>写入文件
     * @param msgArray        需要保存的内容
     * @param filePath        需要保存的绝对路径
     * @param isAppend        是否追加文件,true:是,false:否	 */
    public static void writeFile2(String text, String filePath,
            boolean isAppend) {
        if (text == null || text.length() == 0 || filePath == null
                || filePath.length() == 0)
            return;
        RandomAccessFile randomFile = null;

        try {
            if (!isAppend) {// 如果是覆盖文件,则先清空该文件
                File f = new File(filePath);
                if (f.exists()) {
                    FileOutputStream out = new FileOutputStream(filePath,
                            false);
                    out.close();
                }
            }
            createLastDIR(filePath);
            randomFile = new RandomAccessFile(filePath, "rw");
            if (isAppend) {// 如果是追加文件,则将指针移动到文件末尾
                long fileLength = randomFile.length();
                randomFile.seek(fileLength);
            }
            randomFile.writeUTF(text);
        } catch (Exception e) {
            LOG.error("IO出错:", e);
        } finally {
            try {
                if (randomFile != null) {
                    randomFile.close();
                }
            } catch (IOException e) {
                LOG.error("IO出错:", e);
            }
        }
    }

    /** 创建最后一级文件目录 */
    public static void createLastDIR(String distFile) {
        if (isFilePath(distFile)) {
            String last = getLastDIR(distFile);
            File folderFile = new File(last);
            if (!folderFile.exists()) {
                folderFile.mkdirs();
                folderFile = null;
            }
        }
    }

    /**
     * 1. 按缓存大小拷贝文件
     * @param srcFile:  源文件
     * @param distFile: 目地文件	 */
    public static void buffCopyFile(String srcFile, String distFile) {
        // long t1 = System.currentTimeMillis();
        DataInputStream inn = null;
        DataOutputStream out = null;
        try {
            if (isExists(srcFile)) {
                inn = new DataInputStream(
                        new BufferedInputStream(new FileInputStream(srcFile)));
                createLastDIR(distFile);
                out = new DataOutputStream(new BufferedOutputStream(
                        new FileOutputStream(distFile)));

                byte[] data = new byte[inn.available()];// bufferSize
                int i = -1;
                while ((i = inn.read(data)) != -1) {
                    // out.write(data);
                    out.write(data, 0, i);
                }
            } else {
                LOG.warn("系统未找到源文件:" + srcFile);
            }
        } catch (FileNotFoundException e) {
            LOG.error("未找到文件:", e);
        } catch (IOException e) {
            LOG.error("IO出错:", e);
        } finally {
            try {
                if (inn != null)
                    inn.close();
                if (out != null)
                    out.close();
            } catch (IOException e) {
                LOG.error("IO出错:", e);
            }
        }
        // System.out.println("【Java基本的IO缓存拷贝】花费时间"
        // + (System.currentTimeMillis() - t1) + "毫秒");
    }

    /**
     * 2. 新IO中的基于channel和direct buffer
     * @param inFile
     * @param outFile	 */
    @SuppressWarnings("resource")
    public static void buffFileCopy(String inFile, String outFile) {
        // long t1 = System.currentTimeMillis();
        FileChannel inChannel = null;
        FileChannel ouChannel = null;
        try {
            if (isExists(inFile)) {
                inChannel = new FileInputStream(new File(inFile)).getChannel();
                createLastDIR(outFile);
                ouChannel = new FileOutputStream(new File(outFile))
                        .getChannel();
                ByteBuffer buffer = ByteBuffer.allocateDirect(1024);// bufferSize

                @SuppressWarnings("unused")
                int i = -1;
                while ((i = inChannel.read(buffer)) != -1) {
                    buffer.flip();
                    ouChannel.write(buffer);
                    buffer.clear();
                }
                /*
                 * while (true) { buffer.clear(); if ((i =
                 * inChannel.read(buffer)) == -1) break; buffer.flip();
                 * ouChannel.write(buffer); }
                 */
            } else {
                LOG.warn("系统未找到源文件:" + inFile);
            }
        } catch (FileNotFoundException e) {
            LOG.error("文件未找到", e);
        } catch (IOException e) {
            LOG.error("IO出错:", e);
        } finally {
            try {
                if (inChannel != null)
                    inChannel.close();
                if (ouChannel != null)
                    ouChannel.close();
            } catch (IOException e) {
                LOG.error("IO出错:", e);
            }
        }
        // System.out.println("【新IO中的基于channel和direct buffer】花费时间"
        // + (System.currentTimeMillis() - t1) + "毫秒");
    }

    /**
     * 3. 新IO中的直接映射,MappedByteBuffer
     * @param inFile
     * @param outFile	 */
    public static void byteMapFileCopy(String inFile, String outFile) {
        // long t1 = System.currentTimeMillis();
        // 修改关闭Stream by赵利恒

        FileChannel out = null;
        FileChannel in = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;

        // MappedByteBuffer buffer = null;
        try {
            File file = new File(inFile);
            if (isExists(file)) {
                createLastDIR(outFile);
                inStream = new FileInputStream(file);
                outStream = new FileOutputStream(new File(outFile));
                in = inStream.getChannel();
                out = outStream.getChannel();

                // out = new FileOutputStream(new File(outFile)).getChannel();
                out.transferFrom(in, 0, in.size());

                // buffer = in.map(FileChannel.MapMode.READ_ONLY, 0,
                // file.length());
                // buffer = new FileInputStream(file).getChannel().map(
                // FileChannel.MapMode.READ_ONLY, 0, file.length());
                //
                // buffer.load();
                // out.write(buffer);
                //
                // buffer = null;
                out.close();
            } else {
                LOG.warn("系统未找到源文件:" + inFile);
            }
        } catch (FileNotFoundException e) {
            LOG.error("映射文件失败", e);
        } catch (IOException e) {
            LOG.error("映射文件失败", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (outStream != null) {
                    outStream.close();
                }
                if (in != null) {
                    in.close();
                }
                if (inStream != null) {
                    inStream.close();
                }
            } catch (Exception e) {
                LOG.error("映射文件失败", e);
            }
        }

        // System.out.println("【新IO中的直接映射】花费时间" + (System.currentTimeMillis() -
        // t1) + "毫秒");
    }

    /**
     * 删除文件开头的headCount 行
     * 删除文件结尾的tailCount行
     * @param path
     * @param count	 */
    public static void cutHeadAndTail(String path, int headCount,
            int tailCount) {

        File file = new File(path);
        String lastPath = getLastDIR(path);
        // String filaName= file.getName();

        long totalLineCount = getTotalLineCount(path);
        if (isExists(file)) {
            String tempPath = lastPath + file.getName() + "_tmp.txt";
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(file));
                    BufferedWriter writer = new BufferedWriter(
                            new FileWriter(tempPath, true))) {
                int lineNo = 0;
                while (reader.ready()) {
                    String line = reader.readLine();
                    lineNo++;
                    // 前面N行不写继续往下读
                    if (lineNo <= headCount) {
                        continue;
                    }
                    // 后面N行不写 ,直接跳出循环
                    if (lineNo >= totalLineCount - tailCount + 1) {
                        break;
                    }
                    writer.write(line);
                    writer.write("\n");
                }
                reader.close();
                writer.flush();
                writer.close();
                // 删除原来的文件
                FileUtils.delete(path);
                // 把刚刚生成的文件copy 回 原来的文件里面
                FileUtils.byteMapFileCopy(tempPath, path);
                // 删除临时文件
                if (isExists(tempPath))
                    FileUtils.delete(tempPath);

            } catch (FileNotFoundException e) {
                LOG.error("文件没有找到", e);
            } catch (IOException e) {
                LOG.error("IO操作失败", e);
            }
        }
    }

    /**
     * 获取文件总行数
     * @param path
     * @return	 */
    public static long getTotalLineCount(String path) {
        long count = 0;
        File file = new File(path);
        if (isExists(file)) {
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(file))) {
                String line = reader.readLine();
                while (line != null) {
                    count++;
                    line = reader.readLine();
                }
                reader.close();

            } catch (IOException e) {
                LOG.error("IO操作失败", e);
            }
        }
        return count;
    }

    /**
     * 获取文件数据的长度大小
     * @param filePath        文件的绝对路径
     * @return long           文件的数据大小	 */
    public static long getFileSize(String filePath) {
        long lineSize = 0l;
        if (FileUtils.isFilePath(filePath)) {
            File file = new File(filePath);
            if (FileUtils.isExists(file)) {
                try (RandomAccessFile randomFile = new RandomAccessFile(file,
                        "rw");) {
                    lineSize = randomFile.length();
                } catch (Exception e) {
                    LOG.error("IO操作失败", e);
                }
            }
        } else {
            LOG.error("非法的文件路径: " + filePath);
        }
        return lineSize;
    }

    /**
     * 获取文件数据内容中隐含的最大索引
     * @param filePath        文件的绝对路径
     * @param fieldBar        字段域之间的栅栏
     * @param indexN          索引字段域所在的索引	 */
    public static long getMaxIndex(String filePath, String fieldBar,
            int indexN) {
        long index = 0l;
        if (FileUtils.isFilePath(filePath)) {
            File file = new File(filePath);
            if (FileUtils.isExists(file)) {
                try (RandomAccessFile randomFile = new RandomAccessFile(file,
                        "rw")) {
                    long fileLength = randomFile.length();
                    randomFile.seek(fileLength - 1);// TODO 指针移向最后1行
                    String line = randomFile.readLine();
                    if (StringTools.contains(line, fieldBar)) {
                        String[] sl = line.split(fieldBar);
                        if (indexN >= 0 && indexN < sl.length) {
                            index = Long.valueOf(sl[indexN]);
                        }
                    }
                } catch (FileNotFoundException e) {
                    LOG.error("文件未找到", e);
                } catch (IOException e) {
                    LOG.error("IO操作失败", e);
                }
            }
        }
        return index;
    }

    /** 修改源文件的内容到目标文件中 */
    public static boolean modifyFile(String srcFile, String destFile,
            Map<String, String> contents) {
        boolean flag = false;

        File in = new File(srcFile);
        if (contents != null && !contents.isEmpty() && FileUtils.isExists(in)) {
            try (BufferedReader reader = new BufferedReader(new FileReader(in));
                    FileOutputStream fos = new FileOutputStream(destFile);
                    OutputStreamWriter osw = new OutputStreamWriter(fos);
                    BufferedWriter writer = new BufferedWriter(osw);) {
                boolean isFind = false;// 是否存在
                String line = null, key = null;
                while (reader.ready()) {
                    line = reader.readLine();
                    if (!StringTools.isTrimNull(line)) {
                        Iterator<String> itr = contents.keySet().iterator();
                        while (itr.hasNext()) {
                            key = itr.next();
                            isFind = StringUtils.containsIgnoreCase(line, key);
                            if (isFind)
                                break;
                            key = null;
                        }
                        if (isFind && !StringTools.isTrimNull(key)) {
                            line = StringUtils.replace(line, key,
                                    contents.get(key));
                            contents.remove(key);
                        }

                        // 回写
                        writer.write(line);
                        writer.newLine();
                    } else {
                        writer.write("");
                        writer.newLine();
                    }
                    isFind = false;
                    line = null;
                    key = null;
                }

                flag = contents.isEmpty();// 是否将所有的内容都全部找到并修改
                if (!flag) {
                    LOG.warn("源:" + srcFile);
                    LOG.warn("TO:" + destFile);
                    LOG.warn("文件内容修改未完全,如下:");
                    Iterator<String> itr = contents.keySet().iterator();
                    while (itr.hasNext()) {
                        key = itr.next();
                        LOG.warn(key + " | " + contents.get(key));
                    }
                }

                writer.flush();
                fos.close();
                osw.close();
            } catch (FileNotFoundException e) {
                LOG.error("修改文件内容出错:", e);
                LOG.error(srcFile);
                flag = false;
            } catch (IOException e) {
                LOG.error("修改文件内容出错:", e);
                LOG.error(srcFile);
                flag = false;
            }
        }
        return flag;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值