IO流
文件替换 Files.move()? ?
import java.io.*;
import java.nio.file.*;
public class RenameFile {
//path1 source path2 target
public static boolean renameFile(Path path1, Path path2) throws NoSuchFileException, FileAlreadyExistsException {
//if (Files.notExists(path1)) //debug.txt不存在
// throw new NoSuchFileException(path1.toString());
//if (Files.exists(path2)) //backup.txt已经存在
// throw new FileAlreadyExistsException(path2.toString());
try {
//Files.copy(path1, path2, StandardCopyOption.COPY_ATTRIBUTES); //复制文件属性
//Files.delete(path1); //生成新的backup.txt文件后删除原有的debug.txt(即重命名)
Files.move(path1,path2,StandardCopyOption.REPLACE_EXISTING); //替换已存在的文件
return true;
} catch (IOException e) {
System.out.println("in method");
e.printStackTrace();
return false;
}
}//renameFile
public static void main(String args[]) {
Path source = Paths.get("F:\\temp\\debug.txt");
Path target = Paths.get("F:\\temp\\backup.txt");
try{
if(renameFile(source,target))
System.out.println("Rename File Successful");
else{
System.out.println("Rename File Error"); //此语句不会被执行,因为此时有异常发生
}
}catch(NoSuchFileException e){
System.out.println("debug.txt doesn't exit"); //提示debug.txt文件不存在
e.printStackTrace();
}catch(FileAlreadyExistsException e){
System.out.println("backup.txt already exits"); //提示backup.txt文件已经存在
e.printStackTrace();
}
}
}
异常经解决后不会延续,除非有新的
package com.homework.chapter13_7;
import java.io.*;
import java.nio.file.*;
public class RenameFile {
//path1 source path2 target
public static boolean renameFile(Path path1, Path path2) throws NoSuchFileException, FileAlreadyExistsException {
if (Files.notExists(path1)) //debug.txt不存在
throw new NoSuchFileException(path1.toString());
if (Files.exists(path2)) //backup.txt已经存在
throw new FileAlreadyExistsException(path2.toString()); //throw后即退出到外层main函数调用处
try {
Files.copy(path1, path2, StandardCopyOption.COPY_ATTRIBUTES); //复制文件属性
Files.delete(path1); //生成新的backup.txt文件后删除原有的debug.txt(即重命名)
//Files.move(path1,path2,StandardCopyOption.REPLACE_EXISTING); //直接替换已存在的文件,move方法,使用时注释掉throw new出来的FileAlreadyExistsException
return true;
} catch (IOException e) { //该catch块对应的是上面的try块,但如果已经发生了debug.txt不存在或者backup.txt不存在的情况,则不会到达
e.printStackTrace(); //如果注释掉以上两个throw的地方,则此处可能会被执行,同时异常已经被处理,会执行main中返回值为false的语句块"Rename File Error"
return false;
}
}//renameFile
public static void main(String args[]) {
Path source = Paths.get("F:\\temp\\debug.txt");
Path target = Paths.get("F:\\temp\\backup.txt");
try{
if(renameFile(source,target))
System.out.println("Rename File Successful");
else{
System.out.println("Rename File Error"); //此语句不会被执行,因为此时有异常发生
}
}catch(NoSuchFileException e){
System.out.println("debug.txt doesn't exit"); //提示debug.txt文件不存在
e.printStackTrace();
}catch(FileAlreadyExistsException e){
System.out.println("backup.txt already exits"); //提示backup.txt文件已经存在
e.printStackTrace();
}
}
}