1、将File、FileInputStream 转换为byte数组:
File file = new File("file.txt");
InputStream input = new FileInputStream(file);
byte[] byt = new byte[input.available()];
input.read(byt);
2、将byte数组转换为InputStream:
byte[] byt = new byte[1024];
InputStream input = new ByteArrayInputStream(byt);
3、将byte数组转换为File:
File file = new File('');
OutputStream output = new FileOutputStream(file);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write(byt);
- public static byte[] getStreamBytes(InputStream is) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = is.read(buffer)) != -1) {
- baos.write(buffer, 0, len);
- }
- byte[] b = baos.toByteArray();
- is.close();
- baos.close();
- return b;
- }
- default byte[] readFileBytes(InputStream is){
- byte[] data = null;
- try {
- if(is.available()==0){//严谨起见,一定要加上这个判断,不要返回data[]长度为0的数组指针
- return data;
- }
- data = new byte[is.available()];
- is.read(data);
- is.close();
- return data;
- } catch (IOException e) {
- LogCore.BASE.error("readFileBytes, err", e);
- return data;
- }
- }