注册 登录
编程论坛 JAVA论坛

求大佬解一下

蓄力小绵羊 发布于 2018-04-30 20:29, 1764 次点击
/*3、运用递归将D:\\kstest文件夹下所有的图片复制到D盘下“pictures”文件夹中。(12分)
PS:格式只需考虑:jpg、png、gif;
需要判断“pictures”文件夹是否存在;若不存在则用代码创建该文件夹
D:\\kstest文件夹可以手动创建,可以放一些测试数据*/
public class Text23_03 {
    public static void main(String[] args) {
        //下创建源文件对象和目标对象
        File src = new File ("D:\\kstest");
        File dest = new File("D:\\pictures");
        
    }
   
    public static void copyPhoto (File src , File dest) {
        //判断文件是不否存在
        if (!dest.exists()) {
            dest.mkdir();
        }
        //判断是不是一个文件
        if (src.isDirectory()) {
            File[] files = src.listFiles();
            //遍历数组
            for (File file : files) {
                //再次判断是不是文件
                if (file.isFile()) {
                    
                    if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png") || file.getName().endsWith("gif") ) {
                        
                    }
                }
            }
        }
    }
}
7 回复
#2
疯狂的小a2018-04-30 20:53
你这个代码是运行出来了还是没有运行出来,还是说你不理解这个代码?
#3
林月儿2018-04-30 21:09
有什么好处?
#4
疯狂的小a2018-04-30 21:18
回复 3楼 林月儿
谈好处,显得好俗气
#5
林月儿2018-04-30 21:46
程序代码:
package com.huawei.test;

import import import import import java.nio.channels.FileChannel;

public class FileUtil {
    public static void main(String[] args) throws IOException {
        File src = new File ("D:\\kstest");
        File dest = new File("D:\\pictures");
        copy(src, dest);
    }
    private static void copy(File src, File dest) {
        if(src.isDirectory()) {
            if(!dest.isDirectory()) {
                dest.mkdirs();
            }
            for(File file:src.listFiles()) {
                copy(file, new File(dest, file.getName()));
            }
        } else if(src.isFile()) {
            fileChannelCopy(src, dest);
        }
    }
    public static void fileChannelCopy(File srcFile, File dstFile) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            fileInputStream = new FileInputStream(srcFile);
            fileOutputStream = new FileOutputStream(dstFile);
            inputChannel = fileInputStream.getChannel();
            outputChannel = fileOutputStream.getChannel();
            inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                inputChannel.close();
                fileOutputStream.close();
                outputChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
#6
林月儿2018-04-30 21:58
楼主作业贴要多思考才有收获,刚刚是开玩笑的。。。
楼主加油!
#7
蓄力小绵羊2018-04-30 22:03
回复 6楼 林月儿
来武汉请你吃大餐>>怎么样?谢谢啦!
#8
蓄力小绵羊2018-04-30 22:04
回复 2楼 疯狂的小a
不会做啊
1