Andreas Neophytou
Andreas Neophytou

Reputation: 151

Java: Use parallel stream to copy files

I am studying computer science at a University, and I have been assigned to create a 'normal' program, a program using implicit concurrency (parallel streams) and a program using explicit concurrency (threadpool)

I have created a batch file copier (source to destination) using the Java.NIO lib. I am trying to figure out how it would be possible to be done using parallel streams.

I have a String array which contains the file paths/names, and then I have this loop in order to copy the files to the destination:

int i = 0;
while (i < filelist.length){
    String filepath = filelist[i];
    Path source = Paths.get(filepath);
    Path target = Paths.get(FileBrowser.destinationpath+"/"+filenames[i]);  

    try {
        //replace existing file using java nio package
        System.out.println(Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING));
    } catch (IOException e) {
        e.printStackTrace();
    }
    i++;
}

Any help on how to do this by using parallel streams would be appreciated.

PS. I know that copying files in parallel would not result in the files being copied faster rather than sequential, since it is not a CPU matter and more of a disk matter. Either way this assignment is to test and report results so that's why I have chosen this approach.

Upvotes: 2

Views: 2163

Answers (1)

Jaims
Jaims

Reputation: 1575

Using Java 8, you can iterate over any list as a parallel stream. So using your code, you could do something as the following:

Arrays.asList(filelist).parallelStream().forEach((filepath) -> {
    Path source = Paths.get(filepath);
    Path target = Paths.get(FileBrowser.destinationpath+"/"+filepath]);
    try {
        //replace existing file using java nio package
        System.out.println(Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING));
    } catch (IOException e) {
        e.printStackTrace();
    }
});

Upvotes: 1

Related Questions