【小程序】利用java I/O流技术实现一个照片拷贝功能

/*

* 说明:

* 1.设计思想:想读取文件,然后立即写入;

* 2.关闭原则:先开的后关,后开的先关;


*/

package com.michael.iodetail;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

/*

*

*/

public class Demo3 {

public static void main(String[] args){

copyPhoto(); //调用拷贝函数

}

//照片拷贝函数

public static void copyImage(){

//1.定位源文件和目标文件的位置

File srcFile = new File("C:\\DSC_0303.jpg");

File desFile = new File("G:\\lin.jpg");

//2.构建文件输入和输出通道

FileInputStream srcInput = null;

FileOutputStream desOutput = null;

int length = 0;

byte[] buf = new byte[2024];//缓冲数组

//捕获异常

try{

srcInput = new FileInputStream(srcFile);

desOutput = new FileOutputStream(desFile);

//3.读取数据到内存,并从内存写数据到硬盘(内存是中转站)

while((length = srcInput.read(buf))!=-1){

desOutput.write(buf,0,buf.length);

}

}catch(IOException e){

System.out.println("拷贝文件出错...");

throw new RuntimeException(e);

}finally{

try{

if(desOutput != null){

desOutput.close();

System.out.println("写入资源关闭成功");

}

}catch(IOException e){

System.out.println("关闭文件失败");

throw new RuntimeException(e);

}finally{

try{

if(srcInput != null){

srcInput.close();

System.out.println("读入资源关闭成功");

}

}catch(IOException e){

System.out.println("读入资源关闭失败!");

throw new RuntimeException(e);

}

}

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容