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

        前言:项目有个需求,就是将文件转换为字节流,然后转成字符串,为了验证文件是否正确转换为字节流,从网上找了这个工具类,由于不知道是哪里找的,暂时些微原创,有需要的,代码直接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;
}


版权声明:本文为wangwenzhe222原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。