java 按字节读写二进制文件(Base64编码解码)

最近在做项目时遇到这样一个需求:依次读取本地文件夹里所有文件的内容,转为JSON,发送到ActiveMQ的消息队列, 然后从MQ的消息队列上获取文件的信息,依次写到本地。常见的文件类型,比如.txt 和.png等文件的读写并不难。但是,我刚才所提到的需求,如果用常规的方法去读写,比如按字节读取文件内容,转为字符串,再转为JSON发送到MQ的队列,然后从MQ获取原文件信息写到文件,就会发现写出来的文件和文件不一样。我的解决方法是:按字节读取原文件,转为字节数组,将字节数组转为Base64编码格式的字符串,然后转为JOSN发送到MQ,然后从MQ获取到JOSN,将文件内容通过Base64解码为字符数组,写文件到某个路径。以下为代码:

测试类 Test.class




/**
 * @Desc: 测试类
 * @Date: 2016/7/1
 * @Version: 1.0
 * @Author: lzy
 */
public class Test {
    public static void main(String[] args){

        String fileName="JUBE99EGRR311800";           //文件名:测试文件是没有后缀名的二进制
        String fileReadPath="d:/read/";               //文件所在文件夹
        String filePath=fileReadPath+fileName;        //文件路径

        //工具类
        FileUtil fileUtil=new FileUtil();

        //按字节读取文件内容,并转换为Base64编码字符串
        String fileJsonStr=fileUtil.fileToJson(fileName,filePath);

        //文件内容Base64解码,按字节写文件
        fileUtil.writeFile(fileJsonStr,"d:/write/");
    }
}123456789101112131415161718192021222324

FileUtil.class 文件转换工具类



/**
 * @Desc: 文件内容转换工具类
 * @Date: 2016/7/1
 * @Version: 1.0
 * @Author: lzy
 */

public class FileUtil {

    /**
     * 文件内容转为 Base64 编码的 JSON
     * @param fileName 文件名
     * @param filePath 文件路径
     * @return
     */
    public String fileToJson(String fileName,String filePath){

        String fileContentJson="";      //文件内容转JSON
        try {
            if(null!=filePath && !filePath.equals("")){
                if(null!=fileName && !fileName.equals("")){
                    //将文件内容转为字节数组
                    byte[] fileByte=toByteArray(filePath);

                    //将字节数组转为Base64编码
                    String fileContent=ByteToBase64(fileByte);

                    FileEntity fileEntity=new FileEntity();
                    fileEntity.setFileName(fileName);
                    fileEntity.setFileContent(fileContent);

                    //实体转JSON
                    fileContentJson = FileEntitytoJSON(fileEntity);
                }
            }
        }catch (Exception e){
            Log.error("fileToJson error",e);
        }

        return fileContentJson;
    }

    /**
     * 将文件转成字节数组
     * @param filePath
     * @return
     */
    public byte[] toByteArray(String filePath){

        ByteArrayOutputStream bos=null;
        BufferedInputStream in = null;
        try {
            File f = new File(filePath);
            if(f.exists()){
                in = new BufferedInputStream(new FileInputStream(f));
                bos = new ByteArrayOutputStream((int) f.length());

                int buf_size = 1024;
                byte[] buffer = new byte[buf_size];
                int len = 0;
                while (-1 != (len = in.read(buffer, 0, buf_size))) {
                    bos.write(buffer, 0, len);
                }
                //return bos.toByteArray();
            }

        } catch (IOException e) {
            Log.error("toByteArray() Exception", e);
        } finally {
            try {
                in.close();
                bos.close();
            } catch (IOException e) {
                Log.error("toByteArray() Exception",e);
            }
        }
        return bos.toByteArray();
    }

    /**
     * Base64加密
     * @param b
     * @return
     */
    public String ByteToBase64(byte[] b) {
        String str="";
        if(null!=b){
            BASE64Encoder encoder = new BASE64Encoder();
            str=encoder.encode(b);
        }
        return str;
    }

    /**
     * Base64解密
     * @param str
     * @return
     */
    public byte[] Base64toByte(String str) {
        byte[] b = new byte[0];
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            if(null!=str && !str.equals("")){
                b = decoder.decodeBuffer(str);
            }
        } catch (IOException e) {
            Log.error("Base64toByte() Exception",e);
        }
        return b;
    }

    /**
     * 实体转JSON
     * @param fileEntity
     * @return
     */
    public String FileEntitytoJSON(FileEntity fileEntity) {
        String str="";
        if(null!=fileEntity){
            JSONObject json = JSONObject.fromObject(fileEntity);
            str = json.toString();
        }
        return str;
    }

    /**
     * JSON转实体
     * @param msg
     * @return
     */
    public FileEntity JSONtoFileEntity(String msg) {
        FileEntity fileEntity=new FileEntity();
        if(null!=msg && !msg.equals("")){
            JSONObject obj = new JSONObject().fromObject(msg);
            fileEntity = (FileEntity) JSONObject.toBean(obj, FileEntity.class);
        }
        return fileEntity;
    }

    /**
     * 写文件
     * @param fileJson json
     * @param filePath 文件路径
     */
    public void writeFile(String fileJson,String filePath){
        FileOutputStream fos=null;
        try{

            if(null!=fileJson && !fileJson.equals("")){
                if(null!=filePath && !filePath.equals("")){
                    //json转为文件实体
                    FileEntity fileEntity=JSONtoFileEntity(fileJson);

                    //Base64文件内容解码
                    byte[] b=Base64toByte(fileEntity.getFileContent());

                    File file=new File(filePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }

                    fos = new FileOutputStream(filePath + File.separator +fileEntity.getFileName());
                    fos.write(b);
                }
            }

        }catch (Exception e){
            Log.error("write Exception:",e);
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                Log.error("fos.close() Exception:", e);
            }
        }

    }
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178

FileEntity.class 文件实体类

/**
 * @Desc:文件信息实体
 * @Date: 2016/6/29
 * @Version: 1.0
 * @Author: lzy
 */
public class FileEntity {
    private String fileName;       //文件名
    private String fileContent;    //文件内容

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileContent() {
        return fileContent;
    }

    public void setFileContent(String fileContent) {
        this.fileContent = fileContent;
    }
}

猜你喜欢

转载自www.cnblogs.com/firstdream/p/10070587.html