import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class CreateAbsolutePathFile {
public static void main(String[] args) throws IOException {
if (args.length < 1)
return;
String firstPath = args[0];
String beCopiedFilePath = args[1];
File file = new File(firstPath);
//如果复制到的文件夹没有则创建
if (!file.exists()) {
file.mkdirs();
} else if (beCopiedFilePath != null && beCopiedFilePath.length() > 0) {
copyFile(beCopiedFilePath, firstPath);
}
}
public static void copyFile(String oldPathFile, String newPathFile) {
int byteread = 0;
int byteCount = 0;
File oldfile = new File(oldPathFile);
//用spilit方法实际是在用正则表达式进行匹配,java中//由于转义符代表为/,所以实际为//,又在正则表达式中//代表/所以表示/
//而在不需要正则表达式的方法如String的replace则可以用//表示/这点需要注意
String[] fileName = oldPathFile.split("");
String name = fileName[fileName.length - 1];
boolean isSuccessful = true;
if (oldfile.exists()) { // 文件存在时
try {
InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
BufferedInputStream bufferedInputStream = new BufferedInputStream(inStream);
//复制到的文件必须是具体的文件不能是文件夹,如果为文件夹则出现拒绝访问的异常,所以加上name
FileOutputStream fs = new FileOutputStream(newPathFile + "//" + name);
BufferedOutputStream bufferedOutPutStream = new BufferedOutputStream(fs);
byte[] buffer = new byte[1024 * 5];
while ((byteread = bufferedInputStream.read(buffer)) != -1) {
byteCount += byteread;
bufferedOutPutStream.write(buffer, 0, byteread);
}
inStream.close();
bufferedInputStream.close();
fs.close();
bufferedOutPutStream.close();
} catch (IOException e) {
System.out.println("读取文件出错!原因" + e.getMessage());
isSuccessful = false;
}
} else {
System.out.println("地址" + oldPathFile + "不存在文件");
isSuccessful = false;
}
if (isSuccessful)
System.out.println("复制成功!共复制" + byteCount + "字节");
}
}