java File获取字节流

/*文件64位编码*/
public static void main(String[] args) {
byte[] fileByte = toByteArray(newFile);
String imgStr = new BASE64Encoder().encode(fileByte);
}

/*读取文件的字节数组*/
public static byte[] toByteArray(File file) throws IOException {
File f = file;
if (!f.exists()) {
throw new FileNotFoundException("file not exists");
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}

posted @ 2019-03-04 14:44  洞玄巅峰  阅读(8992)  评论(0编辑  收藏  举报