zoukankan      html  css  js  c++  java
  • Java文件操作之创建、读取、删除、复制,文字生成png图片,下载网络文件

    工具类功能:
      1.通过文件路径获取相关信息,如文件名称;
      2.生成新的文件地址,根据时间生成的文件名称;
      3.读取、复制、删除文件;
      4.根据文本字体大小生成背景透明的png图片;

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.Transparency;
    import java.awt.font.FontRenderContext;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.channels.FileChannel;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    import javax.imageio.ImageIO;
    
    /**
     * 工具类功能:
     *     1.通过文件路径获取相关信息
     *     2.生成新的文件地址
     *     3.读取、复制、删除文件
     *     4.根据文本字体大小生成背景透明的png图片
     * @author maxinhai
     *
     */
    public class FileUtils {
        
         /**
         * 程序可处理视频类型
         */
        private static Set<String> fileTypeSet = new HashSet<>();
        
        static {
            fileTypeSet.add("mp4");
            fileTypeSet.add("flv");
            fileTypeSet.add("avi");
            fileTypeSet.add("rm");
            fileTypeSet.add("rmvb");
            fileTypeSet.add("wmv");
        }
        
        /**
         * 获取指定文件的后缀名
         * @param file
         * @return
         */
        public static String getFormat(File file) {
            String fileName = file.getName();
            String format = fileName.substring(fileName.indexOf(".") + 1);
            return format;
        }
        
        /**
         * 读取某个文件夹下的所有视频文件
         *
         * @param filePath 要读取的路径
         * @return
         */
        public static List<String> readDic(String filePath) {
            List<String> fileList = new ArrayList<>();
            File file = new File(filePath);        //获取其file对象
            readDic(file, fileList);
            return fileList;
        }
    
    
        /**
         * 读取目录
         *
         * @param file
         * @param fileList
         */
        private static void readDic(File file, List<String> fileList) {
            File[] fs = file.listFiles();
            for (File f : fs) {
                //若是目录,则递归打印该目录下的文件
                if (f.isDirectory()) {
                    readDic(f, fileList);
                }
                //若是文件,直接打印
                if (f.isFile() && isVideo(f.getAbsolutePath().toString())) {
                    fileList.add(f.getAbsolutePath().toString());
                }
            }
        }
    
    
        /**
         * 判断文件不否是视频
         *
         * @param fileName
         * @return
         */
        public static boolean isVideo(String fileName) {
            if (fileName.indexOf(".") == -1) {
                return false;
            }
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            return fileTypeSet.contains(fileType);
        }
        
        
        /**
         * 获得视频文件格式
         *
         * @param videoPath
         * @return
         */
        public static String getVideoSuffix(String videoPath) {
            return videoPath.substring(videoPath.lastIndexOf("."));
        }
        
        /**
         * 根据文件路径获取文件名
         * @param filePath
         * @return 不带文件格式的文件名
         */
        public static String getFileName(String filePath) {
            int startIndex = filePath.lastIndexOf("\");
            return filePath.substring(startIndex+1, filePath.length());
        }
        
        /**
         * 根据文件路径获取文件名称带后缀
         * @param filePath
         * @return
         */
        public static String getFileNameAndSuffix(String filePath) {
            int startIndex = filePath.lastIndexOf("\");
            int lastIndex = filePath.lastIndexOf(".");
            return filePath.substring(startIndex+1, lastIndex);
        }
        
        /**
         * 功能描述 生成新的文件路径
         *
         * @param currentVideo : 原来文件路径
         * @return targetPath : 新的文件路径
         * @author xinhai.ma
         * @date 2020/5/9 14:33
         */
        public static String getNewFilePath(String currentVideo, String folderPath) {
            String targetPath = null;
            if (null == currentVideo) {
                targetPath = folderPath + File.separator + getTimeStr() + ".mp4";
            } else {
                targetPath = folderPath + "\" + getTimeStr() + getVideoSuffix(currentVideo);
            }
            return targetPath;
        }
        
        /**
         * 获得格式化后的当前时间
         *
         * @return
         */
        public static String getTimeStr() {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
            LocalDateTime createTime = LocalDateTime.now();
            return createTime.format(formatter);
        }
        
        
        /**
         * 获取简洁路径
         *
         * @param path 文件路径
         * @return 简洁路径
         */
        public static String getSimplePath(String path) {
            int firstIndex = path.indexOf("\");
            int lastIndex = path.lastIndexOf("\");
            String begin = path.substring(0, firstIndex + 1);
            String end = path.substring(lastIndex, path.length());
            return begin + "..." + end;
        }
        
        
        /**
         * 获取简洁路径集合
         *
         * @param pathList 文件路径集合
         * @return 简洁路径集合
         */
        public static List<String> getSimplePathList(List<String> pathList) {
            List<String> simplePathList = new ArrayList<>(pathList.size());
            pathList.forEach(path -> {
                if (!path.equals("暂无数据")) {
                    simplePathList.add(getSimplePath(path));
                }
            });
            return simplePathList;
        }
        
        
        /**
         * 创建多重文件夹及文件
         *
         * @param folderPath 文件夹路径
         * @param filePath   文件名称及后缀
         */
        public static void createFile(String folderPath, String filePath) {
            File folder = new File(folderPath);
            File file = new File(folderPath + File.separator + filePath);
            if (!folder.isFile() && !folder.exists()) {
                folder.mkdirs();
            }
            if (!file.exists()) {
                try {
                    boolean result = file.createNewFile();
                    if (!result) {
                        System.out.println("创建文件失败! {}" + folderPath + File.separator + filePath);
                    } else {
                        System.out.println("创建文件成功!" + folderPath + File.separator + filePath);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 删除文件
         *
         * @param filePath 文件路径
         * @return 删除结果
         */
        public static boolean deleteFile(String filePath) {
            boolean result = false;
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
                result = true;
            }
            return result;
        }
        
        
        /**
         * 复制文件
         *
         * @param sourcePath 要复制的文件路径
         * @param targetPath 复制到的路径
         */
        public static void copyFile(String sourcePath, String targetPath) {
            FileInputStream fi = null;
            FileOutputStream fo = null;
            FileChannel in = null;
            FileChannel out = null;
            try {
                fi = new FileInputStream(sourcePath);
                fo = new FileOutputStream(targetPath);
                in = fi.getChannel();//得到对应的文件通道
                out = fo.getChannel();//得到对应的文件通道
                in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fi.close();
                    in.close();
                    fo.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        
        /**
         * 同步复制文件
         * @param sourceFolderPath 要复制的文件夹
         * @param targetFolderPath 目标文件夹
         */
        public static void batchCopyFile(String sourceFolderPath, String targetFolderPath) {
            File sourceFolder = new File(sourceFolderPath);
            File targetFolder = new File(targetFolderPath);
            if (!sourceFolder.exists()) {
                new RuntimeException(sourceFolderPath + "路径不存在!");
            }
            if (!targetFolder.exists()) {
                new RuntimeException(targetFolderPath + "路径不存在!");
            }
            if (sourceFolder.isFile()) {
                new RuntimeException(sourceFolderPath + "不是文件夹!");
            }
            if (targetFolder.isFile()) {
                new RuntimeException(targetFolderPath + "不是文件夹!");
            }
            File[] files = sourceFolder.listFiles();
            for(int i=0; i<files.length; i++) {
                String source = files[i].getAbsolutePath();
                String target = targetFolderPath + File.separator + files[i].getName();
                copyFile(source, target);
            }
        }
        
        
        /**
         * 同步复制文件
         * @param filePathList     文件地址集合
         * @param targetFolderPath 目标文件夹
         */
        public static List<String> batchCopyFile(List<String> filePathList, String targetFolderPath) {
            List<String> targetPathList = new ArrayList<>(filePathList.size());
            File targetFolder = new File(targetFolderPath);
            if (!targetFolder.exists()) {
                new RuntimeException(targetFolderPath + "路径不存在!");
            }
            if (targetFolder.isFile()) {
                new RuntimeException(targetFolderPath + "不是文件夹!");
            }
            filePathList.forEach(path -> {
                String target = targetFolderPath + File.separator + getFileName(path);
                copyFile(path, target);
                targetPathList.add(target);
            });
            return targetPathList;
        }
        
        
        /**
         * 根据文字生成png图片,并返回图片路径
         * @param drawStr
         * @param font
         * @param targetPath
         * @return
         */
        public static void createImage(String drawStr, Font font, File targetPath) {
            //获取font的样式应用在str上的整个矩形
            Rectangle2D r= font.getStringBounds(drawStr, new FontRenderContext(AffineTransform.getScaleInstance(1, 1),false,false));
            int unitHeight=(int)Math.floor(r.getHeight());//获取单个字符的高度
            //获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
            int width=(int)Math.round(r.getWidth())+1;
            int height=unitHeight+3;//把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
    
            // 创建图片
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
            Graphics2D g = image.createGraphics();
    
            //设置透明  start
            image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
            g = image.createGraphics();
            //设置透明  end
            g.setFont(font); //设置字体
            g.setColor(Color.ORANGE); //设置颜色
            //g.drawRect(0, 0, width - 1, height - 1); //画边框
            g.drawString(drawStr, 0, font.getSize());
            g.dispose();
            try {
                // 输出png图片
                ImageIO.write(image, "png", targetPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }

    下载网络文件:

    /**
         * 根据httpUrl下载网络文件
         * @param httpUrl
         * @param saveFile
         * @return
         */
        public static boolean httpDownload(String httpUrl, String saveFile) {
            // 1.下载网络文件
            int byteRead;
            URL url;
            try {
                url = new URL(httpUrl);
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
                return false;
            }
    
            try {
                //2.获取链接
                URLConnection conn = url.openConnection();
                //3.输入流
                InputStream inStream = conn.getInputStream();
                //3.写入文件
                FileOutputStream fs = new FileOutputStream(saveFile);
    
                byte[] buffer = new byte[1024];
                while ((byteRead = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteRead);
                }
                inStream.close();
                fs.close();
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

    第23个单身的520节日,祝自己节日快乐!

  • 相关阅读:
    docker设置国内镜像
    asp.net core 构建docker镜像
    asp.net POST 数据
    asp.net core 增加浏览器缓存设置
    .net fx源码
    新项目升级到JFinal3.5之后的改变-着重体验自动依赖注入
    微信小程序教程汇总
    如何注册微信小程序
    JFinal-美女图爬虫-一个不正经的爬虫代码
    投资20万研发的JFinal项目《旅游线路营销管理系统》准备公开课中
  • 原文地址:https://www.cnblogs.com/mxh-java/p/12922118.html
Copyright © 2011-2022 走看看