Skip to content

Instantly share code, notes, and snippets.

@zeroleaf
Created October 4, 2013 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeroleaf/6826305 to your computer and use it in GitHub Desktop.
Save zeroleaf/6826305 to your computer and use it in GitHub Desktop.
Binary file
package com.zeroleaf.util;
import java.io.*;
/**
* User: zeroleaf
* Date: 13-10-4
* Time: 14:11
*
* Generate a binary file (in a byte array) from regular file.<br/>
* and convert a binary file to regular file.
*
*/
public class BinaryFile {
public static byte[] fileInBytes(String filePath) {
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try {
fis = new FileInputStream(filePath);
baos = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int readByte;
while ((readByte = fis.read(temp)) != -1) {
baos.write(temp, 0, readByte);
}
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void bytesToFile(byte[] bytes, String outPath) {
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(outPath));
bos.write(bytes);
bos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment