File的io流与base64

1.file转换为base64 字符串

    @Value("${file.store.path}\\")
    private String path;

 /**
     * 将文件进行base64编码
     * @param file
     * @return
     */
    public String FileToBase64(File file){

        String base64 = null;
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            System.out.println(base64);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String result=encoder.encode(data);
        return result;
    }

2. base64字符串转换为file 的io流,并写入本地,返回文件的大小


    /**
     * 将base64转换为文件并写入本地
     */

    public long  base64ToFile(String base64Str,String filePath,String fileName) {
        long fileSize=0;
        if (base64Str == null && filePath == null) {
            return 0;
        }
        try {
            filePath=path+filePath;
            File file = new File(fileName);
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            if(!file.exists()){
                file.createNewFile();
            }
            filePath=filePath+"\\"+"_"+fileName;
            Files.write(Paths.get(filePath), Base64.getMimeDecoder().decode(base64Str), StandardOpenOption.CREATE);
            File imageFile = new File(filePath);
            fileSize = FileUtils.sizeOf(imageFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileSize;
    }

你可能感兴趣的:(Java,java,开发语言)