学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("您输入的文件地址不存在,请重新输入:"); } } } }有其它更好的写法么,期待您的回复,谢谢咯!