日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

字节流转文件,文件转字节流,字节流和文件互转

發布時間:2023/12/29 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 字节流转文件,文件转字节流,字节流和文件互转 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ? 前言:項目有個需求,就是將文件轉換為字節流,然后轉成字符串,為了驗證文件是否正確轉換為字節流,從網上找了這個工具類,由于不知道是哪里找的,暫時些微原創,有需要的,代碼直接ctrl c,ctrl v即可使用

? ? ? ? 廢話結束,直接上代碼

字節轉文件

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數組轉換成文件* @param bytes byte數組* @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();}}}} }

文件轉字節方法?

/*** 文件轉二進制字節** @param file* @return 字節*/ 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; }

總結

以上是生活随笔為你收集整理的字节流转文件,文件转字节流,字节流和文件互转的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。