java File renameTo 踩坑---windows vs linux

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")));
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。