所有文件转成字节数组用byteArray流
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TestIo8 {
public static void main(String[] args) {
byte[] datas = fileToByteArray("1.jpg");//把文件读取变成字节数组流
System.out.println(datas.length);
byteArrayToFile(datas,"3.jpg");//把字节数组流转保存成文件
}
public static byte[] fileToByteArray(String filePath) {
//创建源
File src = new File(filePath);
//选择流
InputStream fis = null;
ByteArrayOutputStream baos = null;//字符数组输出流
//读取文件转换成字节数组流
try {
fis = new FileInputStream(src);
baos = new ByteArrayOutputStream();
byte[] flush = new byte[1024*10];
int len = -1;
while ((len = fis.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 (fis!= null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void byteArrayToFile(byte[] src,String destPath) {
//保存的文件路径
File dest = new File(destPath);
//选择流
InputStream is = null;
OutputStream os = null;
//把字节数组流转成文件
try {
is = new ByteArrayInputStream(src);
os = new FileOutputStream(dest);
byte[] flush = new byte[1024*10];//文件缓冲器
int len = - 1;
while ((len = is.read(flush)) != -1) {
os.write(flush,0,len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
}
}
}