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) {
Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Stuff").resolve("Sayings.txt");
if (!Files.exists(file)) {
System.err.println(file + " is not exist.");
System.exit(1);
}
file.toAbsolutePath();// 将路径转化为绝对路径,如果已经是绝对路径则原样返回
Path tofile = createBackupFilePath(file);// 创建复制文件路径
try{
FileChannel inCh=(FileChannel)(Files.newByteChannel(file));// filechannel具有更高的功能
WritableByteChannel outCh = Files.newByteChannel(tofile,EnumSet.of(WRITE,CREATE));// 新建写入文件通道
int byteWritten = 0;
long byteCount = inCh.size();
while(byteWritten < byteCount){
// Transfers bytes from this channel's file to the given writable byte channel.
// long transferTo(long position,long count,WritableByteChannel target)
// position是开始位置,count是要读取的字节数,target是目标通道
// 返回的是实际转化的字节数
byteWritten += inCh.transferTo(byteWritten,byteCount - byteWritten,outCh);
}
System.out.printf("File copy complete. %d bytes copied to %s%n", byteCount, tofile);
}catch(IOException e){
e.printStackTrace();
}
}
public static Path createBackupFilePath(Path file){
Path parent = file.getParent();
String name = file.getFileName().toString();// getFilename返回文件名(路径类型),也就是路径中距离根目录最远的
int period = name.indexOf('.');
if(period == -1){
period = name.length();
}
String nameAdd = "_backup";
// 修改路径,建立复制文件路径
Path backup = parent.resolve(name.substring(0,period)+nameAdd+name.substring(period));
while(Files.exists(backup)){// 检测新建的路径是否存在,如果存在则继续在文件名后面加_backup
name = backup.getFileName().toString();
backup = parent.resolve(name.substring(0,period)+nameAdd+name.substring(period));
period += nameAdd.length();
}
return backup;
}
}
java通过通道复制文件transferTo
于 2019-01-30 10:34:20 首次发布
本文介绍了一个使用Java NIO进行文件备份的示例程序。该程序首先检查源文件是否存在,然后创建一个带有备份标记的新文件路径。如果新路径已存在,则在文件名后追加更多备份标记直到找到唯一路径。通过FileChannel从源文件读取数据并将其写入到新文件,完成文件的完整复制。
1528





