SoFunction
Updated on 2025-03-06

How to transfer File and byte[] in Java

Java File and byte[] transfer

1. Convert File to byte[]

public static byte[] getImageStream(String imageUrl, 
									HttpServletRequest request) {

	ServletContext application = ().getServletContext();
	String url = ("/")+imageUrl;
	byte[] buffer = null;
	File file = new File(url);
	FileInputStream fis;
	try {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		fis = new FileInputStream(file);
	    byte[] b = new byte[1024];
        int n;
        while ((n = (b)) != -1) {
		     (b, 0, n);
		}
        ();
        ();
        buffer = ();
        if(()) {
        	 ();
        }
	} catch (FileNotFoundException e) {
		();
	}catch (IOException e) {
		();
	}
	return buffer;
}

2. byte[] to File

public static void readBin2Image(byte[] byteArray, String targetPath) {
	InputStream in = new ByteArrayInputStream(byteArray);
    File file = new File(targetPath);
    String path = (0, ("/"));
    if (!()) {
        new File(path).mkdir();
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = (buf)) != -1) {
            (buf, 0, len);
        }
        ();
    } catch (Exception e) {
        ();
    } finally {
        if (null != fos) {
            try {
                ();
            } catch (IOException e) {
                ();
            }
        }
    }
}

Java byte array converted to binary 0 and 1

You can use the following code to convert the byte array in Java to binary strings of 0 and 1:

byte[] bytes = ...; 
StringBuilder binary = new StringBuilder(); 
for (byte b : bytes) { 
    int val = b; 
    for (int i = 0; i < 8; i++) { 
        ((val &amp; 128) == 0 ? 0 : 1); 
        val <<= 1; 
    } 
} 
(

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.