黑马程序员技术交流社区
标题:
键盘接收两个文件夹,把所有.java的文件拷贝
[打印本页]
作者:
许文搏
时间:
2014-8-14 20:53
标题:
键盘接收两个文件夹,把所有.java的文件拷贝
求解答!
public class Test1 {
public static void main(String[] args) throws Exception {
System.out.println("请输入目标文件夹路径:");
File dest = getDir();
System.out.println("请输入源文件路径:");
File src = getDir();
if (dest.equals(src)){
System.out.println("您输入的文件夹路径相同");
}
else {
copy(dest,src);
}
}
//复制文件
public static void copy(File dest,File src) throws IOException{
File newDir = new File(dest,src.getName());
newDir.mkdir();
File[] subFiles = src.listFiles();
for (File subFile : subFiles) {
if (subFile.isFile() && subFile.getName().endsWith(".java")){
FileInputStream fis = new FileInputStream(subFile);
FileOutputStream fos = new FileOutputStream(new File(newDir,subFile.getName()));
byte[] array = new byte[1024];
int len;
while((len = fis.read(array)) != -1){
fos.write(array,0,len);
}
fis.close();
fos.close();
}
else {
copy(newDir,subFile);
}
}
}
//从控制台接收文件夹
public static File getDir() {
Scanner sc = new Scanner(System.in);
while(true){
String s1 = sc.nextLine();
File file = new File(s1);
if(!file.exists()){
System.out.println("您输入的文件夹路径不存在,请重新输入:");
}
else if (file.isFile()){
System.out.println("您输入的是一个文件路径,请重新输入:");
}
else {
return file;
}
}
}
}
作者:
许文搏
时间:
2014-8-14 20:54
复制整个文件夹没问题,但是加上endswith就不行了.
作者:
yqj
时间:
2014-8-14 23:17
在copy方法的最后 else {
copy(newDir,subFile);
}
加上判断试试 ,及else {
if(subFile.isDirectory()){
copy(newDir, subFile);
}
}
因为 if (subFile.isFile() && subFile.getName().endsWith(".java"))中进入else的subFile可以是一个不以".java"结尾的文件而不是文件夹,下次运行 File[] subFiles = src.listFiles();就会报错
作者:
Fengs
时间:
2014-8-15 10:49
很赞的,但是这个题有点看不太懂!上传的题呀
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2