How to convert the file content into a byte array and return it? For this problem, I offer my first successful code~
package com.succez.task1; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * <p>Copyright: Copyright (c) 2018</p> * <p>succez</p> * @author ZhangJinjin * @createdate May 3, 2018 */ public class fileToBuf { /** * Convert the file content into a byte array and return, if the file does not exist or the read error returns null
* * Here you need to create a byte array buffer in memory, and write the read file byte data into the buffer * Finally convert the byte stream into a byte array and close the resource * Need to catch when file not found exception and input and output exception occur */ public static byte[] file2buf(File fobj){ byte[] buffer = null; try{ if (!fobj.exists()) { return null; } FileInputStream fis = new FileInputStream(fobj); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len=-1; while ((len = fis.read(b)) != -1) { bos.write(b, 0, len); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } return buffer; } /* * Two test cases * */ public static void main(String []args){ File fobj1 = new File("E:\\TestExample\\test1.txt"); byte[] buffer1=fileToBuf.file2buf(fobj1); System.out.println(buffer1); File fobj2 = new File("E:\\TestExample\\test2.docx"); byte[] buffer2=fileToBuf.file2buf(fobj2); System.out.println(buffer2); } }
The result is as follows:
After careful analysis, I think it's pretty good, how can I change it, just kidding!
The process goes through again:
FileInputStream gets input bytes from a file in the filesystem, reading a stream of textual raw bytes.
ByteArrayOutputStream This class implements an output stream in which data is written to a byte array. The buffer grows automatically as data is written. Data can be obtained using toByteArray()
and toString()
.
Keep reading data and writing it to the buffer
Convert to byte array using toByteArray() method.
So, no problem~