我使用下面的代碼來編輯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,因爲它無法找到該文件。 儘管該文件僅存在於正確的目錄中。
我明白了,但爲什麼我的腳本idmlcm.sh在執行此操作後無法調用OIMV2Migration.sh? –
@SurbhiMittal創建像這樣的新對象 - 'newFile = new File(oldFile.getAbsolutePath());'這將創建新文件對象的重命名文件。 –