当前位置:   article > 正文

java实现将二进制文件转换成字节文本,再将字节文本转换成二进制文件_java读取二进制文件并转换为文字

java读取二进制文件并转换为文字

一、说明

今天,项目现场提出这样一种需求:项目中,将项目文件打成zip包进行发布时,由于安全机制的限制,不允许发布二进制文件,因此需要将.zip格式的二进制文件encode成文本文件,再将文本文件上传后decode成.zip格式。

二、直接上代码

1、首先上传统IO实现方式

  1. package com.mzj.pe.codec;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. /**
  7. * @Auther: mazhongjia
  8. * @Date: 2020/9/17 11:26
  9. * @Version: 1.0
  10. */
  11. public interface BinaryTextCodec {
  12. String encode(FileInputStream fileInputStream) throws IOException;
  13. void decode(FileOutputStream outputStream, String text) throws IOException;
  14. public static BinaryTextCodec createBinaryTextCodec(){
  15. return new BinaryTextCodecImpl();
  16. }
  17. }
  1. package com..mzj.pe.codec;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. /**
  7. * @Auther: mazhongjia
  8. * @Date: 2020/9/17 11:28
  9. * @Version: 1.0
  10. */
  11. public class BinaryTextCodecImpl implements BinaryTextCodec {
  12. private static final String TEXT_SPLIT_CHAR = ",";
  13. @Override
  14. public String encode(FileInputStream fileInputStream) throws IOException {
  15. if (fileInputStream == null) {
  16. return null;
  17. }
  18. StringBuilder builder = new StringBuilder();
  19. int i = 0;
  20. while ((i = fileInputStream.read()) != -1) {
  21. builder.append(i + TEXT_SPLIT_CHAR);
  22. }
  23. return builder.toString();
  24. }
  25. @Override
  26. public void decode(FileOutputStream fileOutputStream, String text) throws IOException {
  27. if (fileOutputStream == null || text == null) {
  28. return;
  29. }
  30. String[] lineone = text.split(TEXT_SPLIT_CHAR);
  31. for (int j = 0; j < lineone.length; j++) {
  32. fileOutputStream.write(Integer.valueOf(lineone[j]));
  33. }
  34. fileOutputStream.flush();
  35. }
  36. }
  1. package com.mzj.pe.codec;
  2. import java.io.*;
  3. /**
  4. * @Auther: mazhongjia
  5. * @Date: 2020/9/17 13:55
  6. * @Version: 1.0
  7. */
  8. public class FileTransitionUtil {
  9. private static BinaryTextCodec binaryTextCodec = BinaryTextCodec.createBinaryTextCodec();
  10. public static void binaryToText(String binaryFilePath, String textFilePath) throws IOException {
  11. File binaryFile = new File(binaryFilePath);
  12. if (!binaryFile.exists()) {
  13. System.out.println("转换的二进制文件不存在....");
  14. return;
  15. }
  16. File textFile = new File(textFilePath);
  17. if (!textFile.exists())
  18. textFile.createNewFile();
  19. FileInputStream fileInputStream = null;
  20. BufferedWriter bufferedWriter = null;
  21. try {
  22. fileInputStream = new FileInputStream(binaryFile);
  23. bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(textFile)));
  24. String encoder = binaryTextCodec.encode(fileInputStream);
  25. if (encoder != null) {
  26. bufferedWriter.write(encoder);
  27. bufferedWriter.flush();
  28. System.out.println("成功将【"+binaryFilePath+"】转换成文本文件【"+textFilePath+"】");
  29. }
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. } finally {
  33. if (fileInputStream != null) {
  34. try {
  35. fileInputStream.close();
  36. } catch (IOException ie) {
  37. ie.printStackTrace();
  38. }
  39. }
  40. if (bufferedWriter != null) {
  41. try {
  42. bufferedWriter.close();
  43. } catch (IOException ie) {
  44. ie.printStackTrace();
  45. }
  46. }
  47. }
  48. }
  49. public static void textToBinary(String binaryFilePath, String textFilePath) throws IOException {
  50. File textFile = new File(textFilePath);
  51. if (!textFile.exists()) {
  52. System.out.println("转换的文本文件不存在....");
  53. return;
  54. }
  55. File binaryFile = new File(binaryFilePath);
  56. if (!binaryFile.exists())
  57. binaryFile.createNewFile();
  58. FileOutputStream fileOutputStream = null;
  59. BufferedReader bufferedReader = null;
  60. try {
  61. fileOutputStream = new FileOutputStream(binaryFile);
  62. bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(textFile)));
  63. binaryTextCodec.decode(fileOutputStream, bufferedReader.readLine());
  64. System.out.println("成功将【"+textFilePath+"】转换成二进制文件【"+binaryFilePath+"】");
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. } finally {
  68. if (fileOutputStream != null) {
  69. try {
  70. fileOutputStream.close();
  71. } catch (IOException ie) {
  72. ie.printStackTrace();
  73. }
  74. }
  75. if (bufferedReader != null) {
  76. try {
  77. bufferedReader.close();
  78. } catch (IOException ie) {
  79. ie.printStackTrace();
  80. }
  81. }
  82. }
  83. }
  84. }
  1. package com.mzj.pe.codec;
  2. import java.io.IOException;
  3. /**
  4. * @Auther: mazhongjia
  5. * @Date: 2020/9/17 14:15
  6. * @Version: 1.0
  7. */
  8. public class Demo {
  9. public static void main(String[] args) throws IOException {
  10. FileTransitionUtil.binaryToText("D:\\埃及项目画面说明.doc","D:\\1.txt");
  11. FileTransitionUtil.textToBinary("D:\\1.doc","D:\\1.txt");
  12. FileTransitionUtil.binaryToText("D:\\专题图演示视频.mp4","D:\\2.txt");
  13. FileTransitionUtil.textToBinary("D:\\2.mp4","D:\\2.txt");
  14. FileTransitionUtil.binaryToText("D:\\17年餐费未报销.zip","D:\\3.txt");
  15. FileTransitionUtil.textToBinary("D:\\3.zip","D:\\3.txt");
  16. }
  17. }

2、然后我自己又用NIO实现了一版

  1. package com.mzj.pe.codec.test;
  2. import java.nio.ByteBuffer;
  3. import java.nio.CharBuffer;
  4. import java.nio.channels.FileChannel;
  5. import java.nio.charset.Charset;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. import java.nio.file.StandardOpenOption;
  9. /**
  10. * @Auther: mazhongjia
  11. * @Date: 2020/9/17 14:57
  12. * @Version: 1.0
  13. */
  14. public class Text {
  15. public static void main(String[] args) throws Exception {
  16. Path pathIn = Paths.get("D://原始二进制文件.zip");
  17. Path pathOut = Paths.get("D://1.txt");
  18. FileChannel inputChannel = FileChannel.open(pathIn, StandardOpenOption.READ);
  19. FileChannel outputChannel =FileChannel.open(pathOut,StandardOpenOption.WRITE);
  20. ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
  21. while (true){
  22. byteBuffer.clear();
  23. int read = inputChannel.read(byteBuffer);
  24. if(-1 == read){//此处用-1判断是否读完需要依赖上面的 byteBuffer.clear();
  25. //文件读完了
  26. break;
  27. }
  28. //读到文件中内容了,翻转缓冲区,准备get其中数据
  29. byteBuffer.flip();//本例中从ByteBuffer获取数据没有显示的get,而是将其作为参数传给另一个Channel的write方法,但是也是读其中的数据,所以也要进行翻转
  30. StringBuilder builder = new StringBuilder();
  31. while (byteBuffer.hasRemaining()){
  32. builder.append(byteBuffer.get()+",");//1、将bytebuffer中数据,以字节形式取出,每个字节后追加逗号,形成字符串,以便解析字符串时时按,分割还原字节
  33. }
  34. CharBuffer charBuffer = CharBuffer.allocate(builder.length());//2、定义一个上面生成字符串长度的ChatBuffer
  35. charBuffer.put(builder.toString());//3、将字符串写入CharBuffer(A,B,C,D....)
  36. charBuffer.flip();
  37. Charset charset= Charset.defaultCharset();//4、将CharBuffer数据准备写入outputChannel,写入之前,需要转换成ByteBuffer,转换时需要按照特定字符集编码形式进行转换
  38. ByteBuffer byteBuffe1r=charset.encode(charBuffer);
  39. // byteBuffe1r.flip();
  40. outputChannel.write(byteBuffe1r);//将byteBuffer中内容写入到Channel中//5、将CharBuffer的ByteBuffer数组写入outputChannel
  41. // outputChannel.write(byteTemp);//将byteBuffer中内容写入到Channel中
  42. }
  43. inputChannel.close();
  44. outputChannel.close();
  45. }
  46. }
  1. package com.mzj.pe.codec.test;
  2. import java.nio.ByteBuffer;
  3. import java.nio.CharBuffer;
  4. import java.nio.channels.FileChannel;
  5. import java.nio.charset.Charset;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. import java.nio.file.StandardOpenOption;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /**
  12. * @Auther: mazhongjia
  13. * @Date: 2020/9/17 14:57
  14. * @Version: 1.0
  15. */
  16. public class Text2 {
  17. public static void main(String[] args) throws Exception {
  18. Path pathIn = Paths.get("D://1.txt");
  19. Path pathOut = Paths.get("D://1.zip");
  20. FileChannel inputChannel = FileChannel.open(pathIn, StandardOpenOption.READ);
  21. FileChannel outputChannel =FileChannel.open(pathOut,StandardOpenOption.WRITE);
  22. ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
  23. List<Byte> byteList = new ArrayList<>();
  24. while (true){
  25. byteBuffer.clear();
  26. int read = inputChannel.read(byteBuffer);
  27. if(-1 == read){//此处用-1判断是否读完需要依赖上面的 byteBuffer.clear();
  28. //文件读完了
  29. break;
  30. }
  31. //读到文件中内容了,翻转缓冲区,准备get其中数据
  32. byteBuffer.flip();//本例中从ByteBuffer获取数据没有显示的get,而是将其作为参数传给另一个Channel的write方法,但是也是读其中的数据,所以也要进行翻转
  33. while(byteBuffer.hasRemaining()){
  34. byteList.add(byteBuffer.get());
  35. }
  36. }
  37. byte[] bytes = new byte[byteList.size()];
  38. for (int ii=0;ii<bytes.length;ii++){
  39. bytes[ii] = byteList.get(ii);
  40. }
  41. //1、这里的data,是A,B,C...的字符串形式,也就是原始二进制文件的byte数组的字符串逗号分割形式
  42. String data = new String(bytes,Charset.defaultCharset());//这一步是通过文本的字节数组形式,获取文本内容//2、将文本文件中字节还原成A,B,C,....形式,这里相当于decode,解码字符集要与编码保持一致
  43. //3、下面是还原原二进制文件的字节数组:byte2s
  44. String[] dataspliet = data.split(",");
  45. byte[] byte2s = new byte[dataspliet.length];
  46. for (int ii=0;ii<byte2s.length;ii++){
  47. byte2s[ii] = Byte.valueOf(dataspliet[ii]);
  48. }
  49. //4、下面是根据原二进制文件字节数组封装ByteBuffer
  50. ByteBuffer byteBufferWrite = ByteBuffer.allocate(byte2s.length);
  51. byteBufferWrite.put(byte2s);
  52. byteBufferWrite.flip();
  53. //5、将字节数组写入outputChannel
  54. outputChannel.write(byteBufferWrite);//将byteBuffer中内容写入到Channel中
  55. // outputChannel.write(byteTemp);//将byteBuffer中内容写入到Channel中
  56. inputChannel.close();
  57. outputChannel.close();
  58. }
  59. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/618008
推荐阅读
相关标签
  

闽ICP备14008679号