开发工具类 FileUtils

作者: MrHorse1992 | 来源:发表于2018-06-10 15:50 被阅读163次

    包含常用的文件操作,辅助开发

    
    public class FileUtils {
    
        // 获取指定文件的扩展名
        public static String getFilenameExtension(String srcPath) {
            // 将源路径转换成文件对象
            File file = new File(srcPath);
            if (file.isFile()) {
                String name = file.getName(); 
                String[] exName = name.split("\\."); 
                return exName[exName.length - 1];
            } else {
                return "";
            }
        }
    
        /**
         * 判断文件夹是否存在,如不存在则创建
         */
        public static void isFolderExitAndCreate(String folderName){
            File file = new File(folderName);
            if(!file.exists()){
                file.mkdir();
            }
        }
    
        /**
         * 获取文件MD5值
         * 
         * @param file
         * @return 文件的MD5字符串
         */
        public static String getMd5ByFile(File file) {
            String value = null;
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0,
                        file.length());
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(byteBuffer);
                BigInteger bi = new BigInteger(1, md5.digest());
                value = bi.toString(16);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return value;
        }
        
        /**
         * 获取文件总的大小
         * 
         * @param file 文件
         * @return 文件长度
         */
        public static long getFileLength(File file)
                throws IOException {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            return fis.available();
        }
        
          /**
         * rename 文件重命名
         *
         * @param to
         * @param from
         * @return
         */
         public static File rename(File from, File to) {
             try {
                   String newPath = to.getPath();
                   String oldPath = from.getPath();
                   if (!oldPath.equals(newPath)) {
                         if (!to.exists()) {
                             from.renameTo(to);
                         }
                   }
             } catch (Exception ex) {
    
             }
             return to;
        }
    
         /**
         *  rename 文件重命名
         *
         * @param filePath
         * @param from
         * @param to
         * @return
         */
         public static File rename(String filePath, String from, String to) {
             File newFile = null;
             try {
                   File oldFile = new File(combainPath(filePath, from));
                   newFile = new File(combainPath(filePath, to));
                   rename(newFile, oldFile);
             } catch (Exception ex) {
    
             }
             return newFile;
         }
    
    
        /**
         * 读取文件到二进制
         * @param file
         * @return
         * @throws IOException
         */
        public static byte[] getBytesFromFile(File file)
                throws IOException {
            InputStream is = new FileInputStream(file); 
            long length = file.length();
            
            if (length > Integer.MAX_VALUE) {
                // File is too large
            }
            
            byte[] bytes = new byte[(int) length];
            
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            
            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                throw new IOException("不能读取文件: " + file.getName());
            }
            
            is.close();
            return bytes;
        }
        
        /**
         * 获取标准文件大小,以KB,MB,GB结尾
         * 
         * @param file
         * @return 以KB,MB,GB结尾字符串文件大小 
         * @throws IOException
         */
        public static String getFileSize(File file)
                throws IOException {
          
            if (size < 1024) {  
                return String.valueOf(size) + "B";  
            } else {  
                size = size / 1024;  
            }  
            if (size < 1024) {  
                return String.valueOf(size) + "KB";  
            } else {  
                size = size / 1024;  
            }  
            if (size < 1024) {  
                size = size * 100;  
                return String.valueOf((size / 100)) + "."  
                    + String.valueOf((size % 100)) + "MB";  
            } else {  
                size = size * 100 / 1024;  
                return String.valueOf((size / 100)) + "."  
                    + String.valueOf((size % 100)) + "GB";  
            }      
        }
        
    
        
        /**
         * 检查文件是否存在
         * 
         * @param fileName
         * @return
         * @throws IOException
         */
        public static boolean existFile(String fileName)
                throws IOException {
            File file = new File(fileName);
            if (!file.exists()) {
                throw new IOException("文件未找到:" + fileName);
            }
            return file.exists();
        }
        
        /**
         * 删除文件
         * 
         * @param fileName
         */
        public static void deleteFile(String fileName)
                throws IOException {
            File file = new File(fileName);
            if (!file.exists()) {
                throw new IOException("文件未找到:" + fileName);
            }
            file.delete();
        }
        
        /**
         * 读取文件到字符串
         * 
         * @param fileName
         * @return
         * @throws IOException
         */
        public static String readFile(String fileName)
                throws IOException {
            File file = new File(fileName);
            if (!file.exists()) {
                throw new IOException("文件未找到:" + fileName);
            }
            
            BufferedReader in = new BufferedReader(new FileReader(file));
            StringBuffer sb = new StringBuffer();
            String str = "";
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
            in.close();
            return sb.toString();
        }
    
        /**
         * 删除文件夹
         * 
         * @param folderPath
         *            文件夹路径
         */
        public static void delFolder(String folderPath) {
            // 删除文件夹里面所有内容
            delAllFile(folderPath);
            String filePath = folderPath;
            java.io.File myFilePath = new java.io.File(filePath);
            // 删除空文件夹
            myFilePath.delete();
        }
        
        /**
         * 删除文件夹里面的所有文件
         * 
         * @param path
         *            文件夹路径
         */
        public static void delAllFile(String path) {
            File file = new File(path);
            if (!file.exists()) {
                return;
            }
            if (!file.isDirectory()) {
                return;
            }
            String[] childFiles = file.list();
            File temp = null;
            for (int i = 0; i < childFiles.length; i++) {
            
                if (path.endsWith(File.separator)) {
                    temp = new File(path + childFiles[i]);
                } else {
                    temp = new File(path + File.separator + childFiles[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
                if (temp.isDirectory()) {
                    delAllFile(path + File.separatorChar + childFiles[i]);// 先删除文件夹里面的文件
                    delFolder(path + File.separatorChar + childFiles[i]);// 再删除空文件夹
                }
            }
        }
        
        /**
         * 复制单个文件
         * @param srcFileName 待复制的文件名
         * @param descFileName 目标文件名
         * @param coverlay 如果目标文件已存在,是否覆盖
         * @return 如果复制成功,则返回true,否则返回false
         */
        public static boolean copyFile(String srcFileName,
                String descFileName, boolean coverlay) {
            File srcFile = new File(srcFileName);
          
            if (!srcFile.exists()) {      
                return false;
            }
            else if (!srcFile.isFile()) {
                return false;
            }
            File descFile = new File(descFileName);
            // 判断目标文件是否存在
            if (descFile.exists()) {
                // 如果目标文件存在,并且允许覆盖
                if (coverlay) {
                    if (!FileUtils.delFile(descFileName)) {
                        return false;
                    }
                } else { 
                    return false;
                }
            } else {
                if (!descFile.getParentFile().exists()) {
                    // 如果目标文件所在的目录不存在,则创建目录
                    if (!descFile.getParentFile().mkdirs()) {
                        return false;
                    }
                }
            }
     
            // 复制文件
            int readByte = 0;
            InputStream ins = null;
            OutputStream outs = null;
            try {
                // 打开源文件
                ins = new FileInputStream(srcFile);
                // 打开目标文件的输出流
                outs = new FileOutputStream(descFile);
                byte[] buf = new byte[1024]; 
                while ((readByte = ins.read(buf)) != -1) {
                    // 将读取的字节流写入到输出流
                    outs.write(buf, 0, readByte);
                } 
                return true;
            } catch (Exception e) {
                return false;
            } finally {
                // 关闭输入输出流,首先关闭输出流,然后再关闭输入流
                if (outs != null) {
                    try {
                        outs.close();
                    } catch (IOException oute) {
                        oute.printStackTrace();
                    }
                }
                if (ins != null) {
                    try {
                        ins.close();
                    } catch (IOException ine) {
                        ine.printStackTrace();
                    }
                }
            }
        }
        
        /**
         * 复制文件夹
         * 
         * @param oldPath
         *            String 源文件夹路径 如
         * @param newPath
         *            String 目标文件夹路径
         * @return boolean
         */
        public static void copyFolder(String oldPath, String newPath)
                throws IOException {
            // 如果文件夹不存在 则新建文件夹
            mkdir(newPath);
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + files[i]);
                } else {
                    temp = new File(oldPath + File.separator + files[i]);
                }
                
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/"
                            + (temp.getName()).toString());
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = input.read(buffer)) != -1) {
                        output.write(buffer, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);
                }
            }
        }
        
        /**
         * 移动文件到指定目录
         * 
         * @param oldPath
         *            包含路径的文件名 
         * @param newPath
         *            目标文件目录
         */
        public static void moveFile(String oldPath, String newPath)
                throws IOException {
            copyFile(oldPath, newPath);
            deleteFile(oldPath);
        }
        
        /**
         * 移动文件到指定目录,不会删除文件夹
         * 
         * @param oldPath
         *            源文件目录
         * @param newPath
         *            目标文件目录
         */
        public static void moveFiles(String oldPath, String newPath)
                throws IOException {
            copyFolder(oldPath, newPath);
            delAllFile(oldPath);
        }
        
        /**
         * 移动文件到指定目录,会删除文件夹
         * 
         * @param oldPath
         *            源文件目录
         * @param newPath
         *            目标文件目录
         */
        public static void moveFolder(String oldPath, String newPath)
                throws IOException {
            copyFolder(oldPath, newPath);
            delFolder(oldPath);
        }
        
        /**
         * 读取数据
         * 
         * @param inSream
         * @param charsetName
         * @return
         * @throws Exception
         */
        public static String readData(InputStream inSream, String charsetName)
                throws IOException {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = inSream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] data = outStream.toByteArray();
            outStream.close();
            inSream.close();
            return new String(data, charsetName);
        }
        
        /**
         * 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码
         * 
         * @param path
         * @return
         * @throws Exception
         */
        public static Set<String> readFileLine(String path)
                throws IOException {
            Set<String> datas = new HashSet<String>();
            FileReader fr = new FileReader(path);
            BufferedReader br = new BufferedReader(fr);
            String line = null;
            while ((line = br.readLine()) != null) {
                datas.add(line);
            }
            br.close();
            fr.close();
            return datas;
        }    
    }
    
    

    相关文章

      网友评论

        本文标题:开发工具类 FileUtils

        本文链接:https://www.haomeiwen.com/subject/ragfeftx.html