import java.io.*;
import java.util.Scanner;
public class CopyFile {
public static void main(String args[]) {
String src = "d:\\1.txt";
String dest = "d:\\2.txt";
System.out.println("---------------- 文件拷贝 ----------------");
Scanner sca = new Scanner(System.in);
System.out.print("键入要拷贝的源文件路径及文件名:" + src + "\n");
try {
copy(src, dest);
System.out.println("-------文件拷贝成功-------");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
System.out.println("-------文件未找到-------");
} catch (IOException e) {
System.out.println("-------未知原因导致文件读写失败-------");
}
}
/**
* 拷贝目标资源文件中
* @param src:指定目标资源
* @param dest:指定需要写入的文件
* @throws IOException:如果文件读取过程中出现位置错误则抛出IOException
*/
private static void copy(String src, String dest) throws IOException {
// TODO Auto-generated method stub
InputStream in = readFile(src);
writeToFile(in, dest);
}
/**
* 读取文件,并使用InputStream关联读取的文件
* @param src:指定需要读取的文件
* @return 返回与文件相关联的流
* @throws FileNotFoundException
*/
private static InputStream readFile(String src)
throws FileNotFoundException {
// TODO Auto-generated method stub
// 检测文件是否存在
if (!existFile(src)) {
throw new FileNotFoundException("-------指定目标资源不存在-------");
}
// 读取文件
FileInputStream in = new FileInputStream(src);
return in;
}
/**
* 判断文件是否存在
* @param src:需要判断的文件
* @return 如果存在返回true 如果不存在返回false
*/
private static boolean existFile(String src) {
// TODO Auto-generated method stub
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 {
// TODO Auto-generated method stub
if (!existFile(dest)) {
File file = new File(dest);
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(dest);
inToOut(in, out);
}
private static void inToOut(InputStream in, FileOutputStream out)
throws IOException {
// TODO Auto-generated method stub
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();
}
}
}
}
Java实现拷贝文件详细代码
最新推荐文章于 2025-03-29 12:43:22 发布