2017-07-14 43 views
1

我使用下面的代碼來編輯Linux上的文件OIMV2Migration.sh。新的文件沒有被調用renameTo()

String oldFileName = "OIMV2Migration.sh";//file to be edited 
    String tmpFileName = "tmp_try.dat"; //new file containing changes 
    BufferedReader br = null; 
    BufferedWriter bw = null; 
        try { 
        br = new BufferedReader(new FileReader(oldFileName)); 
        bw = new BufferedWriter(new FileWriter(tmpFileName)); 
        String line; 
        while ((line = br.readLine()) != null) { 
         if (line.contains("SURBHI")) { 
          line = line.replace("SURBHI MITTAL" , "SURBHI GUPTA");} 
         bw.write(line+"\n"); 
        } 
        } catch (Exception e) { 
        return; 
        } finally { 
        try { 
         if(br != null) 
          br.close(); 
        } catch (IOException e) { 
         // 
        } 
        try { 
         if(bw != null) 
          bw.close(); 
        } catch (IOException e) { 
         // 
        }} 

       //delete the old file 
        File oldFile = new File(oldFileName);; 
        oldFile.delete(); 
       //rename the new file to old file   
        File newFile = new File(tmpFileName); 
        System.out.println(newFile.getAbsolutePath()); 
        Boolean success = newFile.renameTo(oldFile); 
        System.out.println(newFile.getAbsolutePath()); 

這裏,該文件得到正確既renameTo()之前和renameTo()被執行後更新,但NEWFILE的絕對路徑始終指向「tmp_try.dat。

我從堆棧溢出鏈接知道文件實例的絕對路徑沒有改變,但它仍然是一樣的 但我的問題是我的系統中有另一個文件idmlcm.sh,它在內部調用OIMV2Migration.sh.But之後,此方法執行時,idmlcm.sh無法調用OIMV2Migration.sh,因爲它無法找到該文件。 儘管該文件僅存在於正確的目錄中。

回答

0

根據JAVA Documentation行爲renameTo

這種方法的行爲的許多方面是天生 依賴於平臺的:重命名操作可能無法從移動 文件一個文件系統到另一個文件系統,它可能不是原子的,並且它 可能不會成功,如果具有目標摘要路徑名稱 的文件已存在。應始終檢查返回值以確保 重命名操作成功。

在你的情況下,首先要刪除oldFile比重命名tmpFileoldFileName,實際工作完美,但是當你調用newFile.getAbsolutePath()將打印的tmpFile路徑,因爲Object newFile還是僅指老路。您需要重新創建File Object以訪問您的重命名File

+0

我明白了,但爲什麼我的腳本idmlcm.sh在執行此操作後無法調用OIMV2Migration.sh? –

+0

@SurbhiMittal創建像這樣的新對象 - 'newFile = new File(oldFile.getAbsolutePath());'這將創建新文件對象的重命名文件。 –