首頁 > 軟體

Java實現各種檔案型別轉換方式(收藏)

2022-03-04 13:00:25

1.網路資源轉File

需要引入依賴commons-io

   /**
     * 讀取網路中的圖片
     * @param url https://s3.ap-northeast-1.wasabisys.com/img.it145.com/202203/5bca-hxyuaph9825616rjgcfng0ndi.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;
 
    }
 

到此這篇關於Java 各種檔案型別轉換的方法的文章就介紹到這了,更多相關Java 檔案型別轉換內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com