介绍
本文章向大家介绍怎么在Java将文件和base64字符串进行转换的基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
Java的特点有哪些
Java的特点有哪些 1. java语言作为静态面向对象编程语言的代表,实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。 2. java具有简单性,面向对象,分布式、安全性,平台独立与可移植性,动态性等特点。 3.使用Java可以编写桌面应用程序,网络应用程序,分布式系统和嵌入式系统应用程序等。
需要引入的包:
& lt; dependency> ,,,,,& lt; groupId> commons-codec ,,,,,& lt; artifactId> commons-codec ,,,,,& lt; version> 1.13 & lt;/version> ,,,& lt;/dependency>
源码如下:
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; , , import . io . *; , , public class  Base64FileUtil { , , private 才能static String  targetFilePath =,“E: \ \ base2Img \ \ \ \ test.txt"目标;; , , public 才能;static  void main (String [], args), throws Exception { ,,,String fileStr =, getFileStr (“E: \ \ base2Img \ \ big test.txt"); ,,,System.out.println (“fileStr ===,, +, fileStr); ,,,System.out.println (generateFile (fileStr, targetFilePath)); ,,,System.out.println(“以何种); ,,} , , ,/* * ,,*,文件转化成base64字符串 ,,*,将文件转化为字节数组字符串,并对其进行Base64编码处理 ,,*/public 才能static String  getFileStr (String filePath), { ,,,InputStream 拷贝=,空; ,,,byte [], data =,空; ,,,//,读取文件字节数组 ,,,try { ,,,,,=,拷贝new FileInputStream (filePath); ,,,,,data =, new 字节(in.available ()); ,,,,,in.read(数据); ,,,,,in.close (); ,,,},catch (IOException e), { ,,,,,e.printStackTrace (); ,,,},{finally ,,,,,try { ,,,,,,,in.close (); ,,,,,},catch (IOException e), { ,,,,,,,e.printStackTrace (); ,,,,,} ,,,} ,,,//,对字节数组Base64编码 ,,,BASE64Encoder encoder =, new BASE64Encoder (); ,,,//,返回,Base64 编码过的字节数组字符串 ,,,return encoder.encode(数据); ,,} , , ,/* * ,,*,base64字符串转化成文件,可以是JPEG, PNG, TXT和AVI等等 ,,* ,,*,@param base64FileStr ,,*,@param filePath ,,* @return ,,*,@throws 例外 ,,*/public 才能static boolean  generateFile (String base64FileStr, String filePath), throws Exception { ,,,//,数据为空 ,,,if (base64FileStr ==, null), { ,,,,,System.out.println(“,不行,哎呀!,“); ,,,,,return 假; ,,,} ,,,BASE64Decoder decoder =, new BASE64Decoder (); , , ,,,//,Base64解码,对字节数组字符串进行Base64解码并生成文件 ,,,byte [], byt =, decoder.decodeBuffer (base64FileStr); ,,,for (int 小姐:=,0,,len =, byt.length;,小姐:& lt;, len;, + + i), { ,,,,,//,调整异常数据 ,,,,,if (时代[我],& lt;, 0), { ,,,,,,,时代[我],+=,256; ,,,,,} ,,,} ,,,OutputStream out =,空; ,,,InputStream input =, new ByteArrayInputStream(时代); ,,,try { ,,,,,//,生成指定格式的文件 ,,,,,out =, new FileOutputStream (filePath); ,,,,,byte [], buff =, new 字节[1024]; ,,,,,int len =, 0; ,,,,,while ((=len input.read(浅黄色)),!=,1),{ ,,,,,,,out.write(浅黄色,0,len); ,,,,,} null null null null null null null null null null怎么在Java将文件和base64字符串进行转换