我想要做的是在我更改它之后在我的用户目录中创建一个具有相对路径的新文件。要更改我使用的用户目录System.setProperty("user.dir", "/data");
,然后我创建了一个文件对象,File f2 = new File("f2");
并在我的文件系统上创建了一个空文件f2.createNewFile();
。在此之后,我希望该文件出现在 /data/f2 中,这就是f2.getAbsolutePath()
告诉我的。但是,令人困惑的是,该文件出现在“旧的、初始的”用户目录中。
这是我的测试:
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class Main {
private static FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.startsWith("f")) ? true : false;
}
};
public static void main(String[] args) throws IOException {
String userDirPropertyName = "user.dir";
File initialUserDir = new File(System.getProperty(userDirPropertyName));
System.out.println("files in " + initialUserDir.getAbsolutePath() + ":");
for (File file : initialUserDir.listFiles(filter)) {
System.out.println(" - " + file.getAbsoluteFile());
}
System.out.println("initial userDir = " + System.getProperty(userDirPropertyName));
File f1 = new File("f1");
f1.createNewFile();
System.out.println("f1.getAbsolutePath() = " + f1.getAbsolutePath());
System.out.println("getCanonicalPath() for . = " + new File(".").getCanonicalPath());
System.setProperty(userDirPropertyName, "/data");
System.out.println("changed userDir = " + System.getProperty(userDirPropertyName));
File f2 = new File("f2");
f2.createNewFile();
System.out.println("f2.getAbsolutePath() = " + f2.getAbsolutePath());
System.out.println("getCanonicalPath() for . = " + new File(".").getCanonicalPath());
System.out.println("files in " + initialUserDir.getAbsolutePath() + ":");
for (File file : initialUserDir.listFiles(filter)) {
System.out.println(" - " + file.getAbsoluteFile());
}
}
}
这是我得到的输出:
files in /home/pps/NetBeansProjects/UserDirTest:
initial userDir = /home/pps/NetBeansProjects/UserDirTest
f1.getAbsolutePath() = /home/pps/NetBeansProjects/UserDirTest/f1
getCanonicalPath() for . = /home/pps/NetBeansProjects/UserDirTest
changed userDir = /data
f2.getAbsolutePath() = /data/f2
getCanonicalPath() for . = /data
files in /home/pps/NetBeansProjects/UserDirTest:
- /home/pps/NetBeansProjects/UserDirTest/f1
- /home/pps/NetBeansProjects/UserDirTest/f2
尽管我在两者之间更改了 user.dir,但 f1 和 f2 出现在同一个目录中?