字节流转文件,文件转字节流,字节流和文件互转
生活随笔
收集整理的這篇文章主要介紹了
字节流转文件,文件转字节流,字节流和文件互转
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? ? 前言:項(xiàng)目有個(gè)需求,就是將文件轉(zhuǎn)換為字節(jié)流,然后轉(zhuǎn)成字符串,為了驗(yàn)證文件是否正確轉(zhuǎn)換為字節(jié)流,從網(wǎng)上找了這個(gè)工具類,由于不知道是哪里找的,暫時(shí)些微原創(chuàng),有需要的,代碼直接ctrl c,ctrl v即可使用
? ? ? ? 廢話結(jié)束,直接上代碼
字節(jié)轉(zhuǎn)文件
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException;public class FileTest {public static void main(String[] args) throws Exception{String fileBytes = "";//byte[] bytes = fileBytes.getBytes("utf-8");byte[] bytes = Base64Util.decode(fileBytes);String path = "/Users/wwz/Desktop";fileToBytes(bytes,path,"test.pdf");}/*** 將Byte數(shù)組轉(zhuǎn)換成文件* @param bytes byte數(shù)組* @param filePath 文件路徑 如 D:\\Users\\Downloads\\* @param fileName 文件名*/public static void fileToBytes(byte[] bytes, String filePath, String fileName) {BufferedOutputStream bos = null;FileOutputStream fos = null;File file = null;try {file = new File(filePath + fileName);if (!file.getParentFile().exists()){//文件夾不存在 生成file.getParentFile().mkdirs();}fos = new FileOutputStream(file);bos = new BufferedOutputStream(fos);bos.write(bytes);} catch (Exception e) {e.printStackTrace();} finally {if (bos != null) {try {bos.close();} catch (IOException e) {e.printStackTrace();}}if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}} }文件轉(zhuǎn)字節(jié)方法?
/*** 文件轉(zhuǎn)二進(jìn)制字節(jié)** @param file* @return 字節(jié)*/ public static byte[] getFileToByte(File file) {byte[] bytes = new byte[(int) file.length()];try {InputStream is = new FileInputStream(file);ByteArrayOutputStream bytestream = new ByteArrayOutputStream();byte[] bb = new byte[2048];int ch;ch = is.read(bb);while (ch != -1) {bytestream.write(bb, 0, ch);ch = is.read(bb);}bytes = bytestream.toByteArray();} catch (Exception ex) {ex.printStackTrace();}return bytes; }總結(jié)
以上是生活随笔為你收集整理的字节流转文件,文件转字节流,字节流和文件互转的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: simditor 上传图片 php,La
- 下一篇: 2019 NCNA Contest 题解