将文件转换成byte数组

import java.io.*;
import java.util.Arrays;

public class test {

    public static void main(String[] args) {
       byte[] by = getByteToFile("D:/Test.txt");
        System.out.println(Arrays.toString(by));
    }

    public static byte[] getByteToFile(String physicalFileName){
        File file = new File(physicalFileName);
        byte[] by = new byte[(int)file.length()];
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch = is.read(bb);
            while (ch != -1) {
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            by = bytestream.toByteArray();
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            freeIO(is, null);
        }
        return by;
    }

    public static void freeIO(InputStream is, OutputStream os){
        try {
            if(is != null){
                is.close();
            }
            if(os != null){
                os.close();
            }
        } catch (IOException e) {
            e.getStackTrace();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/ZhenV5/p/12711459.html