控制台程序,除了使用Files类中使用copy()方法将文件复制外,还可以使用FileChannel对象复制文件,连接到输入文件的FileChannel对象能直接将数据传输到连接到输出文件的FileChannel对象中而不涉及显式的缓冲区。
本例用来对命令行参数设定的文件进行复制。文件被复制到一个类似在原始目录下创建的备份文件中。新文件的名称通过在原始文件名称的后面附加多次“_backup”以获得唯一文件名。
1 import static java.nio.file.StandardOpenOption.*; 2 import java.nio.file.*; 3 import java.nio.channels.*; 4 import java.io.IOException; 5 import java.util.EnumSet; 6 7 public class FileBackup { 8 public static void main(String[] args) { 9 if(args.length==0) { 10 System.out.println("No file to copy. Application usage is: " + "java -classpath . FileCopy "filepath"" ); 11 System.exit(1); 12 } 13 Path fromFile = Paths.get(args[0]); 14 fromFile.toAbsolutePath(); 15 16 if(Files.notExists(fromFile)) { 17 System.out.printf("File to copy, %s, does not exist.", fromFile); 18 System.exit(1); 19 } 20 21 Path toFile = createBackupFilePath(fromFile); 22 try (FileChannel inCh = (FileChannel)(Files.newByteChannel(fromFile)); 23 WritableByteChannel outCh = Files.newByteChannel( toFile, EnumSet.of(WRITE,CREATE_NEW))){ 24 int bytesWritten = 0; 25 long byteCount = inCh.size(); 26 while(bytesWritten < byteCount) { 27 bytesWritten += inCh.transferTo(bytesWritten, byteCount-bytesWritten, outCh); 28 } 29 30 System.out.printf("File copy complete. %d bytes copied to %s%n", byteCount, toFile); 31 } catch(IOException e) { 32 e.printStackTrace(); 33 } 34 } 35 36 // Method to create a unique backup Path object under MS Windows 37 public static Path createBackupFilePath(Path file) { 38 Path parent = file.getParent(); 39 String name = file.getFileName().toString(); // Get the file name 40 int period = name.indexOf('.'); // Find the extension separator 41 if(period == -1) { // If there isn't one 42 period = name.length(); // set it to the end of the string 43 } 44 String nameAdd = "_backup"; // String to be appended 45 46 // Create a Path object that is a unique 47 Path backup = parent.resolve( 48 name.substring(0,period) + nameAdd + name.substring(period)); 49 while(Files.exists(backup)) { // If the path already exists... 50 name = backup.getFileName().toString(); // Get the current file name 51 backup = parent.resolve(name.substring(0,period) + // add _backup 52 nameAdd + name.substring(period)); 53 period += nameAdd.length(); // Increment separator index 54 } 55 return backup; 56 } 57 }