Java基础之读文件——使用通道复制文件(FileBackup)

控制台程序,除了使用Files类中使用copy()方法将文件复制外,还可以使用FileChannel对象复制文件,连接到输入文件的FileChannel对象能直接将数据传输到连接到输出文件的FileChannel对象中而不涉及显式的缓冲区。

本例用来对命令行参数设定的文件进行复制。文件被复制到一个类似在原始目录下创建的备份文件中。新文件的名称通过在原始文件名称的后面附加多次“_backup”以获得唯一文件名。

 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);
} System.out.printf("File copy complete. %d bytes copied to %s%n", byteCount, toFile);
} catch(IOException e) {
e.printStackTrace();
}
} // Method to create a unique backup Path object under MS Windows
public static Path createBackupFilePath(Path file) {
Path parent = file.getParent();
String name = file.getFileName().toString(); // Get the file name
int period = name.indexOf('.'); // Find the extension separator
if(period == -1) { // If there isn't one
period = name.length(); // set it to the end of the string
}
String nameAdd = "_backup"; // String to be appended // Create a Path object that is a unique
Path backup = parent.resolve(
name.substring(0,period) + nameAdd + name.substring(period));
while(Files.exists(backup)) { // If the path already exists...
name = backup.getFileName().toString(); // Get the current file name
backup = parent.resolve(name.substring(0,period) + // add _backup
nameAdd + name.substring(period));
period += nameAdd.length(); // Increment separator index
}
return backup;
}
}
上一篇:每天一个linux命令(32):gzip命令


下一篇:C# 定时器-System.Timers.Timer