import
java.io.*;
import
java.nio.file.Files;
import
java.util.concurrent.CountDownLatch;
public
class
GFG {
public
static
void
main(String[] args)
throws
IOException, InterruptedException {
String sourcePath =
"source.txt"
;
String destinationPath =
"destination.txt"
;
int
chunkSize =
1024
*
1024
;
long
fileSize = Files.size(
new
File(sourcePath).toPath());
int
numChunks = (
int
) Math.ceil((
double
) fileSize / chunkSize);
CountDownLatch latch =
new
CountDownLatch(numChunks);
for
(
int
i =
0
; i < numChunks; i++)
{
long
start = i * chunkSize;
long
end = Math.min((i +
1
) * chunkSize, fileSize);
Thread thread =
new
Thread(
new
CopyTask(sourcePath, destinationPath, start, end, latch));
thread.start();
}
latch.await();
System.out.println(
"File copied successfully!"
);
}
static
class
CopyTask
implements
Runnable {
private
String sourcePath;
private
String destinationPath;
private
long
start;
private
long
end;
private
CountDownLatch latch;
public
CopyTask(String sourcePath, String destinationPath,
long
start,
long
end, CountDownLatch latch) {
this
.sourcePath = sourcePath;
this
.destinationPath = destinationPath;
this
.start = start;
this
.end = end;
this
.latch = latch;
}
@Override
public
void
run() {
try
(RandomAccessFile sourceFile =
new
RandomAccessFile(sourcePath,
"r"
);
RandomAccessFile destinationFile =
new
RandomAccessFile(destinationPath,
"rw"
)) {
sourceFile.seek(start);
destinationFile.seek(start);
byte
[] buffer =
new
byte
[
1024
];
int
bytesRead;
while
((bytesRead = sourceFile.read(buffer)) >
0
) {
destinationFile.write(buffer,
0
, bytesRead);
}
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
latch.countDown();
}
}
}
}