JAVA COPYFILE PROCESS

#YEAH,I HAVE TO SAY ,THIS IS BEAUTIFUL CODE.FROM THIS SAMPLE CODE,PLEASE LEARN TO DEBUG FLEXIBLY#

package cn.itcast.eclipse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo2 {

public static void main(String[] args) {

String src = "c:\\1.txt";
String dest = "c:\\2.txt";
try {
copy(src,dest);
System.out.println("拷贝成功!!");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}catch (IOException e) {
System.out.println("由于未知的原因,导致文件读写失败!!");
}
}

/**
* 拷贝目标资源到文件中
* @param src : 指定目标资源
* @param dest :指定需要写入的文件
* @throws IOException : 如果文件读取过程中,出现了未知错误,则会抛出IOException
*/
private static void copy(String src, String dest) throws IOException {
InputStream in = readFile(src);
writeToFile(in,dest);
}

/**
* 读取文件,并使用InputStream关联需要读取的文件
* @param src : 指定需要读取的文件
* @return: 返回与文件相关联的流
* @throws FileNotFoundException
*/
private static InputStream readFile(String src) throws FileNotFoundException {

//1.检测文件是否存在
if(!existFile(src)){
throw new FileNotFoundException("指定目标资源不存在!!");
}
//2.读取文件
FileInputStream in = new FileInputStream(src);
return in;
}

/**
* 判断文件是否存在
* @param src : 需要判断的文件
* @return :如果存在则返回true,否则false
*/
private static boolean existFile(String src) {

File file = new File(src);
if(file.exists()){
return true;
}
return false;
}

/**
*
* @param in
* @param dest
* @throws IOException
*/
private static void writeToFile(InputStream in, String dest) throws IOException {

if(!existFile(dest)){
File file = new File(dest);
file.createNewFile();
}

FileOutputStream out = new FileOutputStream(dest);
inToOut(in,out);

}

/**
*
* @param in
* @param out
* @throws IOException
*/
private static void inToOut(InputStream in, FileOutputStream out) throws IOException {
try{
int len = 0;
byte buffer[] = new byte[1024];
while((len=in.read( buffer))>0){
out.write(buffer,0,len);
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值