File 文件地址转换相关方法

1.网络资源转File

需要引入依赖commons-io

   /**
     * 读取网络中的图片
     * @param url https://www.kziyue.com/wp-content/uploads/2019/06/5bca-hxyuaph9825616.jpg
     * @return
     */
    public File URLToFile(String url){
        File file1 = new File("test.png");
        try {
 
            URL url1 = new URL(url);
            FileUtils.copyURLToFile(url1,file1);
 
        } catch (IOException e) {
            e.printStackTrace();
        }
        File absoluteFile = file1.getAbsoluteFile();
        return file1;
    }

 

 

2.网络资源转MultipartFile

需要引入依赖spring-web

 /**
     * 文件上传
     * @param urlStr url地址
     * @return multipartFile
     */
    public MultipartFile fileUpload(String urlStr) throws Exception {
        try {
            //把地址转换成URL对象
            URL url = new URL(urlStr);
            //创建http链接
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //截取链接中的文件名
            String fileName= urlStr.substring(urlStr.lastIndexOf("/")+1);
            MultipartFile multipartFile = new MockMultipartFile(fileName,fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
 
            return multipartFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception();
 
    }

 

 

3.File转MultipartFile

需要引用的依赖spring-text,httpcore

    /**
     * 文件类型转换
     *
     * @param filePath 文件file
     * @return MultipartFile
     */
    public static MultipartFile caseFileToMultipartFile(File filePath) {
        MultipartFile multipartFile = null;
        try {
            log.info("开始进行文件转换");
            FileInputStream fileInputStream = new FileInputStream(filePath);
            multipartFile = new MockMultipartFile(filePath.getName(), filePath.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return multipartFile;
    }

 

 

4.File转字节数组

 /**
     * 将文件转为字节数组
     * @param file 
     * @param size 1024
     * @return
     */
    public static byte[] BufferStreamForByte(File file, int size) {
        byte[] content = null;
        try {
            BufferedInputStream bis = null;
            ByteArrayOutputStream out = null;
            try {
                FileInputStream input = new FileInputStream(file);
                bis = new BufferedInputStream(input, size);
                byte[] bytes = new byte[1024];
                int len;
                out = new ByteArrayOutputStream();
                while ((len = bis.read(bytes)) > 0) {
                    out.write(bytes, 0, len);
                }
 
                bis.close();
                content = out.toByteArray();
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return content;
 
    }

 

 

5.Frame转BufferedImage

需要引入依赖javacv

 public static BufferedImage FrameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }

 

 

6.BufferedImage转MultipartFile

 
 public static MultipartFile fileCase(BufferedImage image){
        //得到BufferedImage对象
       // BufferedImage bufferedImage = JoinTwoImage.testEncode(200, 200, url);
        MultipartFile multipartFile= null;
        try {
            //创建一个ByteArrayOutputStream
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //把BufferedImage写入ByteArrayOutputStream
            ImageIO.write(image, "jpg", os);
            //ByteArrayOutputStream转成InputStream
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            //InputStream转成MultipartFile
            multipartFile =new MockMultipartFile("file", "file.jpg", "text/plain", input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return multipartFile;
 
    }

 

7. 复制单个文件

/**
     * 复制单个文件
     * @param oldPath String 原文件路径 如:c:/fqf.txt
     * @param newPath String 复制后路径 如:f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            File fileUploadFile = new File(newPath.substring(newPath.lastIndexOf("\\")));
            if (!fileUploadFile.exists()) {
                fileUploadFile.mkdirs();
            }
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }

 

posted @ 2022-09-27 15:08  曹丽是我女朋友。  阅读(503)  评论(0编辑  收藏  举报