Categories
Mastering Development

copy contents of one file to another file based on folder files data in java?

I am trying to do a file structure and the text contents.

I have folder called "Basedir" and the subdirectory and files structure.

 Basedir
 -a.csv(base file)
 -b.csv(base file)
 /Basedir/srcdir/
    a.csv (source related file)
    c.csv (src related file)
    /Basedir/srcdir/subDir/
        a.csv(subdir related file)
        
Basedir/src2dir/
    a.csv (src2 data)
    d.csv ( src2 data)

Output is like fileshas to be generated as in the below directory structure:

   Dir:srcDir/
   file: a.csv (src data relatedfile)
   file: b.csv(base data related file)
   file:  c.csv (src data related file)

   Dir:srcDir/subdir/
   file:  a.csv(subdir folder related file)
   file:  b.csv(base folder related file)
   file:  c.csv (src data related file)

   Dir:src1
   file:  a.csv (src1 data related file)
   file:  b.csv(base data related file)
   file:  d.csv (src1 data related file)

I have tested with the files of same name in different folders.How can i achieve for the above scenario.Pls suggest me changes in the below code.

public class Demo {

public static void main(String[] args) {

    String fromDirectory = "/Workspace/Basedir/";
    String toToDirectory = "/Workspace/Output/";

    try {

        copyDirectoryJavaNIO(Paths.get(fromDirectory),
            Paths.get(toToDirectory));

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Done");

}

public static void copyDirectoryJavaNIO(Path source, Path target)
        throws IOException {

    if (Files.isDirectory(source)) {

        if (Files.notExists(target)) {
            
            Files.createDirectories(target);
            System.out.println("Directory created : " + target);
        }

        try (Stream<Path> paths = Files.list(source)) {

            // recursive loop
            paths.forEach(p ->
                    copyDirectoryJavaNIOWrapper(
                      p, target.resolve(source.relativize(p)))
            );

        }

    } else {
        // if file exists, replace it
        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
        System.out.println(
                String.format("Copy File from \t'%s' to \t'%s'", source, target)
        );
    }
}

// extract method to handle exception in lambda
public static void copyDirectoryJavaNIOWrapper(Path source, Path target) {

    try {
        copyDirectoryJavaNIO(source, target);
    } catch (IOException e) {
        System.err.println("IO errors : " + e.getMessage());
    }

  }

 }

Leave a Reply

Your email address will not be published. Required fields are marked *