The method of converting between file and Byte array in JAVA
The method of converting between files and Byte arrays in JAVA is as follows:
public class FileUtil { // Convert the file to Byte array public static byte [] getBytesByFile(String pathStr) { File file = new File(pathStr); try { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000 ); byte [] b = new byte [1000 ]; int n; while ((n = fis.read(b)) != -1 ) { bos.write(b, 0 , n); } fis.close(); byte [] data = bos.toByteArray() ; bos.close(); return data; } catch (Exception e) { e.printStackTrace(); } return null ; } // Convert Byte array to file public static void getFileByBytes( byte [] bytes, String filePath, String fileName) { BufferedOutputStream bos = null ; FileOutputStream fos = null ; File file = null ; try { File dir = new File(filePath); if (! dir.exists() && dir.isDirectory()) { // Determine whether the file directory exists dir.mkdirs(); } file = new File(filePath + "\\" +fileName); 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(); } } } } }
0 Comments