复制文件时,文件夹中有同名的文件时,自动给文件重命名

学java基础的IO流,想起windows的复制文件的操作,当文件夹中有同名的文件时,可以自动给文件重命名。想起学过的IO流的知识,也想自己实现一下,码了下面的代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

/**
*
*/
public class Demo5 {

   public static void main(String[] args) throws IOException {
      File file1 = getFile();
      File file2 = getFile();
      copyFile(file1, file2, check(file1, file2));
   }

   public static void copyFile(File file1, File file2, String s) throws IOException {
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1));
      BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2 + "\\" + s));
      System.out.println();
      int b;
      while ((b = bis.read()) != -1) {
         bos.write(b);
      }
      bis.close();
      bos.close();
   }

   public static String check(File file1, File file2) {
      String s = file1.getName().substring(0, file1.getName().length() - (file1.getName().lastIndexOf(".")) - 1);
      String s1 = file1.getName().substring(file1.getName().length() - (file1.getName().lastIndexOf(".")) - 1);
      File file3 = new File(file2.getPath() + "\\" + file1.getName());
      File[] arr = file2.listFiles();
      int num = 1;
      for (File file : arr) {
         String str = s + "-" + num++;
         if (file.getName().startsWith(s)) {
            if (file.getName().equals(str + s1)) {

            } else {
               return str + s1;

            }
         } else {
            return file1.getName();
         }
      }
      return file1.getName();
   }

   public static File getFile(){
      Scanner sc = new Scanner(System.in);
      while(true){
         System.out.println("请输入文件地址:");
         String s = sc.nextLine();
         File file = new File(s);
         if(file.exists()){
            if(file.isDirectory()){
               System.out.println("您输入的是文件夹地址,请输入文件地址:");
            }else{
               return file;
            }
         }else{
            System.out.println("您输入的文件地址不存在,请重新输入:");
         }
         
      }
   }

}
有其它更好的写法么,期待您的回复,谢谢咯!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值