两个工具类

一:File转 64


     * File转成编码成 64
     */
 
    public static  String fileTo 64(String path) {
        String  64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
             64 =  64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  64;
    }

二: 64转File

public static void  64ToFile(String  64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath=\"D:\\\\image\";
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes =  64.getDecoder().decode( 64);
            file=new File(filePath+\"\\\\\"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

测试一下

public static void main(String[] args) {
          64ToFile(fileTo 64(\"D:\\\\images\\\\haha.jpg\"), \"haha.jpg\");
     }

 

收藏 打印