gpt4 book ai didi

java - 新文件未在 renameTo() 上被调用

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:48 27 4
gpt4 key购买 nike

我使用以下代码在 linux 上编辑文件 OIMV2Migration.sh。

    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());

此处,文件已正确更新,但 newFile 的绝对路径始终指向“tmp_try.dat”,无论是在执行 renameTo() 之前还是执行 renameTo() 之后。

我从堆栈溢出链接了解到文件实例的绝对路径不会改变,它保持不变。但我的问题是我的系统中有另一个文件 idmlcm.sh,它在内部调用 OIMV2Migration.sh。但是执行此方法后,idmlcm.sh 无法调用 OIMV2Migration.sh,就好像找不到该文件一样。尽管该文件仅存在于正确的目录中。

最佳答案

根据 JAVA Documentation

renameTo 的行为:

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

在你的例子中,首先你要删除 oldFile 然后将 tmpFile 重命名为 oldFileName,这实际上是完美的,但是当你调用newFile.getAbsolutePath() 将打印 tmpFile 的路径,因为 Object newFile 仍然只引用旧路径。您需要重新创建 File Object 才能访问重命名的 File

关于java - 新文件未在 renameTo() 上被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45095495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com