Java File renameTo 方法 Windows Linux 下的差異:
window :
1 在關(guān)閉源文件之前,進(jìn)行重命名操作,返回 false,重命名失?。?
2 目標(biāo)文件存在時(shí),返回false,重命名失敗。
linux:
1 在關(guān)閉源文件之前,進(jìn)行重命名操作,返回 true,重命名成功;
2 目標(biāo)文件存在時(shí),返回true,覆蓋已存在的同名目標(biāo)文件,重命名成功。
測(cè)試demo:(注:使用jdk1.6)
public static void testRename() throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String str = sdf.format(new Date());
String outFileTemp = "testRename" + str + ".txt";
Writer writer = null;
try{
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileTemp, false), "GBK"));
writer.write("789");
writer.flush();
/*
* 1.關(guān)閉流前重命名
*/
File tempFile = new File(outFileTemp);
System.out.println(tempFile.renameTo(new File("testRename.txt")));
}catch(Exception e){
System.out.println("Exception is:" + e.getMessage());
}finally{
try{
if(writer != null){
writer.close();
}
} catch (IOException e) {
System.out.println("關(guān)閉流對(duì)象失敗:" + e.getMessage());
}
}
/*
* 2.關(guān)閉流后再重命名
*/
// File tempFile = new File(outFileTemp);
// System.out.println(tempFile.renameTo(new File("testRename.txt")));
}