栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

java中pdf写成base64文件流

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java中pdf写成base64文件流

package com.yellowcong.voice.utils;

import java.io.ByteArrayInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.Base64;

public class Base64Utils {

private static Base64Utils utils = null;

private Base64Utils(){

}

public static Base64Utils getInstance(){

if(utils == null){

synchronized (Base64Utils.class) {

if(utils == null ){

utils = new Base64Utils();

}

}

}

return utils;

}

public int getFileSize(File inFile){

InputStream in = null;

try {

in = new FileInputStream(inFile);

//文件长度

int len = in.available();

return len;

}catch (Exception e) {

// TODO: handle exception

}finally{

try {

in.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return -1;

}

public String file2Base64(File inFile){

//将文件转化为字节码

byte [] bytes = copyFile2Byte(inFile);

if(bytes == null){

return null;

}

//base64,将字节码转化为base64的字符串

String result = Base64.getEncoder().encodeToString(bytes);

return result;

}

private byte [] copyFile2Byte(File inFile){

InputStream in = null;

try {

in = new FileInputStream(inFile);

//文件长度

int len = in.available();

//定义数组

byte [] bytes = new byte[len];

//读取到数组里面

in.read(bytes);

return bytes;

} catch (Exception e) {

e.printStackTrace();

return null;

}finally{

try {

if(in != null){

in.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

public boolean base64ToFile(String strBase64,File outFile){

try {

// 解码,然后将字节转换为文件

byte[] bytes = Base64.getDecoder().decode(strBase64); // 将字符串转换为byte数组

return copyByte2File(bytes,outFile);

} catch (Exception ioe) {

ioe.printStackTrace();

return false;

}

}

private boolean copyByte2File(byte [] bytes,File file){

FileOutputStream out = null;

try {

//转化为输入流

ByteArrayInputStream in = new ByteArrayInputStream(bytes);

//写出文件

byte[] buffer = new byte[1024];

out = new FileOutputStream(file);

//写文件

int len = 0;

while ((len = in.read(buffer)) != -1) {

out.write(buffer, 0, len); // 文件写操作

}

return true;

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

try {

if(out != null){

out.close();

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return false;

}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984778.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号