package java02;
/**
* 我的java每天100行代码008
* I/O流:利用文件输入流,文件输出流,字节数组输入流,字节数组输出流,来实现图片的拷贝
*
* @author Administrator
*
*/
import java.io.*;
//I/O流的常规操作步骤:创建源,选择流,操作(读与写),释放资源
//对于字节数组的操作可以没有创建源课释放资源两个部分,因为字节数组属于在虚拟机内部操作,由gc来负责资源回收
//需要知道I/O流中的四大抽象类,每一个抽象类中常规方法的使用
public class java0093 {
public static void main(String[] args) {
byte[] dates =fileToByteArray("3.jpg");//用变量表示方法的返回值
System.out.println(dates.length);
byteArrayToFile(dates,"5.jpg");
}
//图片读取到字节数组中
//图片到程序,程序到字节数组
public static byte[] fileToByteArray(String filePath) {
//创建源,字节数组可以没有源头
File src = new File(filePath);
//选择流
InputStream in =null;
ByteArrayOutputStream baos = null;
try {
//操作
in = new FileInputStream(src);
baos = new ByteArrayOutputStream();
byte[] flush = new byte[1024];//创建容器的方式
int len = -1;
while((len = in.read(flush))!=-1) {
baos.write(flush,0,len);
}
baos.flush();
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//释放资源
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//字节数组转换成图片
//字节数组到程序,程序到图片
public static void byteArrayToFile(byte[] dates,String s) {
//创建源,字节数组可以没有源头
File f = new File(s);
//选择流
ByteArrayInputStream ba = null;
OutputStream out = null;
try {
ba = new ByteArrayInputStream(dates);
out = new FileOutputStream(f);
//操作
byte[] b =new byte[1024];
int l=-1;
while((l=ba.read(b))!=-1) {
out.write(b,0,l);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
//释放资源,字节数组可以不用释放资源
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java100-009:I/O流:利用文件输入流,文件输出流,字节数组输入流,字节数组输出流,来实现图片的拷贝
最新推荐文章于 2023-01-17 23:32:39 发布