Created
October 4, 2013 13:56
-
-
Save zeroleaf/6826305 to your computer and use it in GitHub Desktop.
Binary file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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