package file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class CopyFile
{
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
//输入数据源的路径
System.out.println("请输入源文件目录:");
Scanner in = new Scanner(System.in);
String str = in.next();
//将字符串类型转换为文件类型
File file = new File(str);
System.out.println("请输入目标文件目录:");
Scanner out = new Scanner(System.in);
String str2 = out.next();
//将字符串类型转换为文件类型
File file2 = new File(str2);
// File file = new File("F:\\国信安\\msg\\美景\\0001.jpg");
// File file2 = new File("F:\\copy");
//判断源文件是否存在
if (file.exists())
{
FileInputStream fis = null;
FileOutputStream fos = null;
//获取源文件的绝对路径
String path = file.getAbsolutePath();
// System.out.println(path);
//截取文件的名称
String fileName = path.substring(path.lastIndexOf("\\") + 1, path.length());
System.out.println("copy的文件是:" + fileName);
//在某目录下新建一个和需要复制的文件 名称相同的空文件
File afterFile = new File("" + file2 + "\\" + fileName + "");
System.out.println(afterFile);
//判断目标路径是否存在
if (!afterFile.exists())
{
fis = new FileInputStream(file);
fos = new FileOutputStream(afterFile);
byte[] buffer = new byte[1024];
int length;
//System.out.println("==");
//将源文件的内容写到新建的文件中,如下while里面的写法,解决了buffer里面带来了空格问题。
while ((length = fis.read(buffer)) != -1)
{
fos.write(buffer, 0, length);
// fis.read();
}
System.out.println("copy成功");
} else
{
System.out.println("目标文件已经存在");
}
} else
{
System.out.println("原文件不存在");
}
//结束后关闭输入输出流,,注意的是,如果先打开输入流,那么就最后关闭输入流(先开后关 原则)
fis.close();
fos.close();
}
}