对接流:文件到字节数组是不能直接传递的,要通过程序。以程序为中转点,实现文件和字节数组之间的传递:
* 文件通过程序到字节数组;字节数组通过程序到文件。这个需要用到文本输入流、输出流和字节数组输入流、
* 输出流。
/*
文本读取到字节数组:
1.文本到程序
2.程序到字节数组
*/
public static byte[] fileToByteArray(String path){
//源头与目的地
File file = new File(path);
byte[] destByte = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
is = new FileInputStream(file);
baos = new ByteArrayOutputStream();
//分段读取,实际开发中,一般是几K的读取,1024就是1K,10K=1024*10这样写
byte[] flush = new byte[1024];//缓冲容器
int len = -1;//接收长度
while ((len = is.read(flush))!=-1){
baos.write(flush,0,len);
}
baos.flush();
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null!=is){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/*
字节数组写出到文本
1.字节数组到程序
2.程序到文本
*/
public static void byteArrayToFile(byte[] src,String filePath){
File file = new File(filePath);
InputStream is = null;
OutputStream os = null;
try {
is = new ByteArrayInputStream(src);
os = new FileOutputStream(file);
byte[] data = new byte[3];
int len = -1;
while((len = is.read(data))!=-1){
os.write(data,0,len);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null!=os){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
调用
byte[] datas = fileToByteArray("fileTest.txt");
System.out.println(datas);
byteArrayToFile(datas,"testFile.txt");