class Demo9
{
/*
复制图片
复制d盘的图片到e盘中
像多媒体文件及图片资源,操作它最好使用字节流
因为使用字符流可能会出现无法浏览的情况
*/
public static void main(String[] args)
{
File src=new File("d:\\temp.png");
//获取源文件绝对路径
String srcPath=src.getAbsolutePath();
//获取文件路径截取文件名然后组拼成新的文件路径
String destPath="e:\\"+srcPath.substring(srcPath.lastIndexOf("\\")+1);
File dest=new File(destPath);
copyPic(src,dest);
}
public static void copyPic(File src,File dest){
InputStream fis=null; //要进行初始化
OutputStream fos=null; //要进行初始化
try{
fis=new FileInputStream(src);
fos=new FileOutputStream(dest);
//创建缓冲区
byte[] buffer=new byte[1024];
int len; //记录读取到的数据的个数
while((len=fis.read(buffer))!=-1){
//把读取到的数据写入到文件中
//只写缓冲区中的有效位
fos.write(buffer,0,len);
}
//关闭流:虽说可以不关,但是关上还是好一些
fis.close();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
《黑马程序员》 IO之复制图片
最新推荐文章于 2021-07-24 13:25:29 发布