简单的实现将文件复制到另一路径下,目前只支持单一文件的复制:
package com.jwnie.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
/**
*
* @author jwnie
*
*/
public class FileCopy {
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException {
copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\3\\2.txt");
copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\3\\2");
copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\jwnie");
copyFile("E:\\jwnie\\WeixinUrl.bcp", "F:\\jwnie\\1.txt");
}
/**
*
* @param src
* 文件源
* @param dest
* 文件目的(可存在也可不存在,也可为目录或文件)
* @throws FileNotFoundException
* @throws IOException
* @throws ParseException
*/
public synchronized static void copyFile(String src, String dest)
throws FileNotFoundException, IOException, ParseException {
FileInputStream fis = null;
FileOutputStream fos = null;
File srcFile, destFile;
srcFile = new File(src);
// 利用字节类型的数组,一次性读取1Kb数据再进行传输,比对单个字节读写效率更高
byte[] buf = new byte[1024];
if (srcFile.exists()) {
if (srcFile.isFile()) {
try {
destFile = new File(dest);
if (!destFile.exists()) {// 文件目的路径不存在
if (!destFile.toString().contains(".")) {// 文件目的路径指向目录
destFile.mkdirs();
String str = destFile.getAbsolutePath() + "\\"
+ srcFile.getName();
fos = new FileOutputStream(str);
System.out.println("文件目的路径不存在,且指向目录:" + str);
} else if (destFile.toString().contains(".")) {// 文件目的路径指向文件
int a = destFile.toString().lastIndexOf("\\");
String s = destFile.toString().substring(0, a);
new File(s).mkdirs();
destFile.createNewFile();
fos = new FileOutputStream(dest);
System.out.println("文件目的路径不存在,且指向文件:"
+ destFile.getPath());
}
} else {// 文件目的路径存在
if (destFile.isDirectory()) {// 文件目的路径指向目录
String str = destFile.getAbsolutePath() + "\\"
+ srcFile.getName();
fos = new FileOutputStream(str);
System.out.println("文件目的路径存在,且指向目录:" + str);
} else {// 文件目的路径指向文件
fos = new FileOutputStream(dest);
System.out.println("文件目的路径存在,且指向文件:" + dest);
}
}
fis = new FileInputStream(src);
int i = fis.read(buf, 0, buf.length);
System.out.println("开始复制....");
while (i != -1) {
fos.write(buf, 0, i);
i = fis.read(buf, 0, buf.length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
} else {
System.out.println("目前暂支持文件的复制!");
}
System.out.println("复制成功!");
} else {
System.out.println("找不到指定路径下的文件!");
}
}
}