0

How can I go to each subfolder in a given directory and take a pdf file from there like wise collect all pdf from all subfolders and move to a common folder?.

I've tried below code which is failing.

import java.io.File;
import java.io.IOException;`enter code here`
import java.nio.file.Files;
import java.util.ArrayList;


public class PDFMover{

/** 
 * @param args
 * @return 
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    File mainfolder = new File("C:\\Users\\myuser\\Desktop\\X\\Report");

    File[] fulllist = mainfolder.listFiles();

    ArrayList<String> listofpath = new ArrayList<String>(fulllist.length);


    for (File x : fulllist)    
    {
        if (x.isDirectory())

        {

            System.out.println("Directory:" +x.getName());
        }

        else

        {
            System.out.println("Notfound");
        }
    }

    String source = "C:\\Users\\myuser\\Desktop\\X\\Report";

    String destination ="C:\\Users\\myuser\\Desktop\\Destination";

    File f1 = new File(source);

    File f2 = new File(destination);

    for (File x : fulllist)

    {

        if(mainfolder.isDirectory())

        {

        Files.copy(f1.toPath(), f2.toPath());

        }


    }

 }
}
Pau
  • 14,917
  • 14
  • 67
  • 94
  • Maybe a DUPLICATE to http://stackoverflow.com/questions/20987214/recursively-list-all-files-within-a-directory-using-nio-file-directorystream – Tobias Otto Dec 22 '16 at 12:23

2 Answers2

0

If you use nio.Files the solution to find every file in every subdirectory would be:

import java.nio.file.FileSystems;
import java.nio.file.Files;

public class FileWalker
{
    public static final String PATH = "C:\\Users\\myuser\\Desktop\\X\\Report";

    public static void main(final String[] args) throws Exception
    {
        Files.walk(FileSystems.getDefault()
                              .getPath((PATH)))
             .map(path -> path.getFileName())
             .filter(name -> name.toString()
                                 .toLowerCase()
                                 .endsWith("pdf"))
             .forEach(System.out::println);
    }
}

Instead of System.out.println you have to copy the files.

Tobias Otto
  • 1,634
  • 13
  • 20
  • Hi Otto Thank you. I tried this but there are couple of error I came to know that this is due to Java version 7. – Purna M Jan 02 '17 at 14:22
0

You can either use a recursive function, or use an explicit stack to do this. You simply check each of the files to see if they match your selection criteria. If not and if it's a directory you put it in the stack and move on.

Here's some working code using this approach. It let's you find files with a particular extension down to a particular recurs depth. The getRecurseFiles() returns a list of canonical path strings.

import java.util.*;
import java.io.*;

class Tracker {
    File[] list;
    int depth;

    public Tracker (File[] l, int d) {
        this.list = l;
        this.depth = d;
    }
}

public class RecTraverse {
    public static int MAX_DEPTH = 10;

    List<String> getRecurseFiles (String dir) throws IOException {
        List<String> requiredFiles = new ArrayList<>();
        Stack<Tracker> rstack = new Stack<>();

        File[] list = new File(dir).listFiles();
        rstack.push(new Tracker(list, 1));

        while (!rstack.empty()) {
            Tracker tmp = rstack.pop();

            for (int i=0; i<tmp.list.length; i++) {
                File thisEntry = tmp.list[i];
                String fileName = tmp.list[i].getCanonicalPath();
                if (thisEntry.isFile()) {
                    int j = fileName.lastIndexOf('.');
                    if (j > 0) {
                        String extension = fileName.substring(j+1).toLowerCase();
                        if (extension.equals("pdf"))
                            requiredFiles.add(tmp.list[i].getCanonicalPath());
                    }
                } else {
                    System.out.println(thisEntry.getCanonicalPath());
                    File[] thisEntryList = thisEntry.listFiles();
                    if (thisEntryList != null && tmp.depth+1 <= MAX_DEPTH) {
                        rstack.push(new Tracker(thisEntryList, tmp.depth+1));
                    }
                }
            }
        }
        return requiredFiles;
    }

    public static void main (String[] arg) {
        try {
            List<String> l = new RecTraverse().getRecurseFiles(".");
            for (String s : l)
                System.out.println(s);
        } catch (IOException e) {
        }
    }
}
DebD
  • 373
  • 3
  • 20