使用字节数组读写文件
package IOStudy;
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;
/**
* 对接字节数组流_输入和输出
* 1.图片读取到字节数组
* 2.字节数组写出到文件
* 执行顺序:读文件->写字节数组->程序->读字节数组->写文件
* @author pmc
*
*/
public class ByteArrayIOout3 {
public static void main(String[] args) {
// File src=new File("txt.txt");
// try {
// InputStream in=new FileInputStream(src);
// byte temp=0;
// while((temp=(byte) in.read())!=-1){
// System.out.print((char)temp);
// }
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
byte[] datas=fileToByteArray("abc.png");
byteArrayToFile(datas,"abc_2.png");
}
/**
* 1.图片读取到字节数组
* 1.1 图片到程序FileInputStream
* 1.2 程序到字节数组ByteArrayOutputStream
*/
public static byte[] fileToByteArray(String path){
File src=new File(path);
byte[] dest=null;
if(src.exists()&&src.isFile()){
InputStream in=null;
ByteArrayOutputStream bat=null;
try {
bat=new ByteArrayOutputStream();
in=new FileInputStream(src);
byte[] temp=new byte[1024];
int len=0;
while((len=in.read(temp))!=-1){
bat.write(temp,0,len);
// System.out.println(len);
}
System.out.println("文件字节大小:"+bat.size());
bat.flush();
return bat.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* 2.字节数组写出到文件
* 2.1 字节数组到程序 ByteArrayInputStream
* 2.2 程序到文件 FileOutputStream
*/
public static void byteArrayToFile(byte[] src,String filePath){
File dest=new File(filePath);
InputStream is=null;
OutputStream out=null;
try {
is=new ByteArrayInputStream(src);
out=new FileOutputStream(dest);
byte[] flush=new byte[10];
int len = 0;
while((len=is.read(flush))!=-1){
out.write(flush, 0, len);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package IOStudy;
import java.io.B