Java Reference
In-Depth Information
}
FileBackup.java
This method assumes the argument has already been validated as a real file. You extract the basic in-
formation you need to create the new file first — the parent directory path, the file name, and where the
period separator is, if there is one. You then create a Path variable, backup , that you initialize using the
original file path. The while loop continues as long as backup already exists as a file, and an instance of
"_backup" is appended to the path until a unique filename is arrived at.
You can now write the main() method to use the createBackupFile() method to create the destination
file for the file backup operation:
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.io.IOException;
import java.util.EnumSet;
public class FileBackup {
public static void main(String[] args) {
if(args.length==0) {
System.out.println("No file to copy. Application usage is:\n" +
"java -classpath . FileCopy
\"filepath\"" );
System.exit(1);
}
Path fromFile = Paths.get(args[0]);
fromFile.toAbsolutePath();
if(Files.notExists(fromFile)) {
System.out.printf("File to copy, %s, does not exist.",
fromFile);
System.exit(1);
}
Path toFile = createBackupFilePath(fromFile);
try (FileChannel inCh =
(FileChannel)(Files.newByteChannel(fromFile));
WritableByteChannel outCh = Files.newByteChannel(
toFile,
EnumSet.of(WRITE,CREATE_NEW))){
int bytesWritten = 0;
long byteCount = inCh.size();
while(bytesWritten<byteCount) {
bytesWritten += inCh.transferTo(bytesWritten,
byteCount-bytesWritten,
outCh);
Search WWH ::




Custom Search