最近在做项目时遇到这样一个需求:依次读取本地文件夹里所有文件的内容,转为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;
}
}

java 按字节读写二进制文件(Base64编码解码)的更多相关文章

  1. Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net

    Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net 1. Base64编码, 1 1.1. 子模式 urlsafe Or  url  ...

  2. Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net

    Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net 1. Base64编码,1 1.1. 子模式 urlsafe Or  url u ...

  3. delphi Base64编码/解码及数据压缩/解压知识

    一.Base64编码/解码 一般用到的是Delphi自带的单元EncdDecd,当然还有第三方提供的单元或控件,其中我所接触到的认为比较好的有Indy的TIdMimeEncode / TIdMimeD ...

  4. Delphi Base64编码/解码及ZLib压缩/解压

    最近在写的程序与SOAP相关,所以用到了一些Base64编码/解码及数据压缩/解压方面的知识. 在这里来作一些总结:   一.Base64编码/解码   一般用到的是Delphi自带的单元EncdDe ...

  5. 《PHP 实现 Base64 编码/解码》笔记

    前言 早在去年 11 月底就已经看过<PHP 实现 Base64 编码/解码>这篇文章了,由于当时所掌握的位运算知识过于薄弱,所以就算是看过几遍也是囫囵吞枣一般,不出几日便忘记了其滋味. ...

  6. OpenSSL 使用 base64 编码/解码

    简述 关于 OpenSSL 的介绍及安装请参见:Windows下编译OpenSSL 下面主要介绍有关 OpenSSL 使用 base64 编码/解码. 简述 编码解码 更多参考 编码/解码 #incl ...

  7. 利用openssl进行BASE64编码解码、md5/sha1摘要、AES/DES3加密解密

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  8. Javascript中Base64编码解码的使用实例

    Javascript为我们提供了一个简单的方法来实现字符串的Base64编码和解码,分别是window.btoa()函数和window.atob()函数. 1 var encodedStr = win ...

  9. Code:Base64 编码/解码

    ylbtech-Code:Base64 编码/解码 1. C#返回顶部 1.编码 byte[] inArray = new byte[msgTxt.Length]; int x; ; x < m ...

随机推荐

  1. python之PIL模块基础功能

    Image主要是打开图片后,对图片进行编辑,主要有以下一些常用功能: 1.读取并显示图片: from PIL import Image img = Image.open("H:\\salar ...

  2. ubuntu18.04 运行时提示缺少libstdc++.so.6

    解决方法:输入命令 sudo apt- 提示:ubuntu默认软件包管理器不是yum,而是dpkg,安装软件时用apt-get PS:在ubuntu下最好不要去装yum,不然可能会出现一些奇怪的问题

  3. Android 性能优化-启动时间

    adb shell am start -W -n com.xxxx(包名)/xxx.xxxActivity(launch Activity)

  4. Zabbix4.2.0使用Python连接企业微信报警

    目录 1. 配置企业微信 2. 脚本配置 2.1 安装python依赖的库 2.2 编写脚本 2. 搭建FTP 3. 配置Zabbix监控FTP 3.1 添加FTP模板 3.2 添加报警媒介 3.3 ...

  5. SQL 必知必会·笔记<14>更新和删除数据

    1. 更新数据 基本的UPDATE语句,由三部分组成: 要更新的表 列名和它们的新值 确定要更新那些行的过滤条件 更新单列示例: UPDATE Customers SET cust_email = ' ...

  6. Spring Boot + Spring Cloud 构建微服务系统(三):服务消费和负载(Feign)

    Spring Cloud Feign Spring Cloud Feign是一套基于Netflix Feign实现的声明式服务调用客户端.它使得编写Web服务客户端变得更加简单.我们只需要通过创建接口 ...

  7. Jquery 跨域访问 Lightswitch OData Service

    修改lightswitch .server project web.config.添加如下内容就可以实现对ApplicationData.svc/跨域访问 <system.webServer&g ...

  8. PXE | 开关机

    PXE | 开关机流程 linuxPXE 主要阶段 引导的主要6个阶段 从MBR中读取引导加载程序boot loader 加载并初始化内核: 检测和配置设备: 创建内核进程: 系统管理员干预(单用户模 ...

  9. 使用Asp.Net Core MVC 开发项目实践[第五篇:缓存的使用]

    项目中我们常常会碰到一些数据,需要高频率用到但是又不会频繁变动的这类,我们就可以使用缓存把这些数据缓存起来(比如说本项目的导航数据,帖子频道数据). 我们项目中常用到有Asp.Net Core 本身提 ...

  10. [转]angular2之@Output() EventEmitter

    本文转自:https://www.jianshu.com/p/f2768f927c86 A src/app/components/contains/contain1.ts import { Compo ...