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 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自動生成方法存根
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){
byteWritten+=inCh.transferTo(byteWritten,byteCount-byteWritten,outCh);
//Transfers bytes from this channel's file to the given writable byte channel.
//long transferTo(long position,long count,WritableByteChannel target) position是開始位置,count是要讀取的字節數,target是目標通道
//返回的是實際轉化的字節數
}
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;
}
}
通過通道複製文件transferTo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.