[英]How can a renamed file's path remain unchanged in java?
So I finally changed the name of file1
to another name. 因此,我终于将
file1
的名称更改为另一个名称。 However what makes me frustrated is that the path remain unchanged!Could you please tell me why and how to deal with it since I always need the handler of file1 for further operation?Here is my sample code: 但是令我沮丧的是该路径保持不变!请问一下为什么以及如何处理它,因为我一直需要file1的处理程序才能进行进一步的操作?这是我的示例代码:
import java.io.File;
import java.io.IOException;
public class TestFile {
volatile private static File file1;
volatile private static File file2;
public static void main(String[] args) throws IOException {
file1 = new File("D:\\work\\triangle\\src\\original\\test1.java");
file2 = new File("D:\\work\\triangle\\src\\original\\test2.java");
File tmpFile;
String file2name = file2.getAbsolutePath().toString().replace("\\", "/") + ".bak";
System.out.println(file2name);
String file1name = file1.getAbsolutePath().toString()
.replace("\\", "/");
System.out.println(file1name);
tmpFile = new File(file2name);
if (!file1.renameTo(tmpFile)) {
System.err.println("file1->file2name-bak");
}
System.out.println("file1\t"+file1.getAbsolutePath().toString());
System.out.println("tmpFile\t"+tmpFile.getAbsolutePath().toString());
}
}
and I get those output: 我得到那些输出:
D:/work/triangle/src/original/test2.java.bak
D:/work/triangle/src/original/test1.java
file1 D:\work\triangle\src\original\test1.java
tmpFile D:\work\triangle\src\original\test2.java.bak
How can the file1
and tmpFile
yield different path? file1
和tmpFile
如何产生不同的路径?
You are misunderstanding what a File
is. 您误解了
File
是什么。
A File
denotes a file name / path, not the name / path of a specific file. File
表示文件名/路径,而不是特定文件的名称/路径。 So, when you use a File
to rename a file, the pathname stored in your File
object does not change. 因此,当您使用
File
重命名文件时,存储在File
对象中的路径名不会更改。 A File
object is immutable. File
对象是不可变的。
Then is there any way to change them both?
那么有什么办法可以改变它们两者吗?
No. The name / path encoded in a File
object does not change, and cannot be changed. 否。在
File
对象中编码的名称/路径不会更改,也无法更改。 If you don't believe me, check the source code that is shipped with your JDK. 如果您不相信我,请检查JDK随附的源代码。
(The pathname state of a File
is represented by the String-valued path
attribute. The only places where path
is assigned are the constructors, and the readObject
method.) (
File
的路径名状态由String值的path
属性表示。分配path
的唯一位置是构造函数和readObject
方法。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.