如何将图片从目录和子目录复制到另一个目录?

时间:2013-07-07 12:52:58

标签: java

如何将我写入控制台和子目录的目录中的图片复制到另一个目录。

我从控制台获取目录时遇到问题。

此代码有效但我改变时

private File[] images = new File("C:/Users/Public/Pictures/Sample Pictures"+"/").listFiles() 

new File(path+"/").listFiles() 

它不起作用。

public class Copy {
    private String path;
    private File[] images = new File("C:/Users/Public/Pictures/Sample Pictures"
            + "/").listFiles();

    private Copy() throws IOException {
        getPath();
        finder();
    }

    public static void main(String[] args) throws IOException {
        Copy copy = new Copy();
    }

    private void getPath() {
        System.out.print("Enter directory: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        try {
            path = br.readLine();
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your name!");
            System.exit(1);
        }
    }

    private void finder() throws IOException {
        System.out.println("" + path);
        for (File f : images) {

            if (f.isDirectory()) {
                File[] nextimages = new File(
                        "C:/Users/Public/Pictures/Sample Pictures" + "/"
                                + f.getName()).listFiles();
                for (File z : nextimages) {
                    System.out.println("Processing: " + z.getName() + "...");
                    if (z.isHidden()) {
                        System.out.println("Skipping, file is hidden...");
                        continue;
                    }
                    process(z);
                }
                continue;
            }

            if (f.isHidden()) {
                System.out.println("Skipping, file is hidden...");
                continue;
            }
            process(f);

        }
    }

    private void process(File file) throws IOException {
        BufferedImage image = ImageIO.read(file);
        saveThumbnail(file, image);
    }

    private void saveThumbnail(File originalFile, BufferedImage thumbnail)
            throws IOException {
        String filename = originalFile.getName();
        String fileExt = filename.substring(filename.lastIndexOf('.') + 1);
        ImageIO.write(thumbnail, fileExt, new File("D:/Stahovanie/Zadanie/"
                + filename));
    }
}

1 个答案:

答案 0 :(得分:0)

你有

private String path;
private File[] images = new File("C:/Users/Public/Pictures/Sample Pictures"+"/").listFiles();

所以在开始时pathnull。现在您需要知道在构造函数代码之前初始化字段,因此如果您将images更改为

new File(path+"/").listFiles();

将其更改为

new File(null+"/").listFiles();

所以它会产生

new File("null/").listFiles();

要解决该问题,请尝试调用

images = new File(path+"/").listFiles();

path设置为正确值时,可能在getPath方法之后。