- public class CopyFile {
- static int count = 1;
- public static void main(String[] args) {
- // src源地址路径,desc目标地址路径
- String src = "D:\\a.txt";
- String desc = "D:\\a.txt";
- copyFile(new File(src), new File(desc));
- }
- /**
- * 复制源文件到目标文件的方法
- *
- * @param src
- * @param desc
- */
- private static void copyFile(File srcFile, File descFile) {
- // 检测文件路径是否相同,如果相同,就将目标文件名前加上复件和数字
- if (srcFile.equals(descFile)) {
- descFile = new File(descFile.getParentFile() + File.separator
- + "复件 " + count++ + srcFile.getName());
- }
- try {
- BufferedInputStream bis = new BufferedInputStream(
- new FileInputStream(srcFile));
- // 或者也可以简单的让新文件内容加在源文件之后,需要如下语句:
- // BufferedOutputStream bos = new BufferedOutputStream(
- // new FileOutputStream(descFile,true));
- BufferedOutputStream bos = new BufferedOutputStream(
- new FileOutputStream(descFile));
- byte[] buf = new byte[1024];
- int len = 0;
- while ((len = bis.read(buf)) != -1) {
- bos.write(buf, 0, len);
- bos.flush();
- }
- bos.close();
- bis.close();
- } catch (FileNotFoundException e) {
- System.out.println("找不到源文件");
- } catch (IOException e) {
- System.out.println("写入出错");
- }
- }
- }
复制代码 简单写了一个代码,只是多了个检测把文件名改了下。希望能帮到你
|