如何编写java项目文件夹中文件的相对文件路径



项目名称为" producer "。我有一个文件位于项目文件夹C:/Users/Documents/producer/krb5.conf。如果我想写它的相对路径,我应该写

吗?
File file = new File("krb5.conf");

File file = new File("producer/krb5.conf");

File file = new File("./krb5.conf");

?

您可以同时使用您的1。和3。选择。

2。选项将参考C:/Users/Documents/producer/producer/krb5.conf.

为了进行测试,您可以尝试从每个文件中获取绝对路径并将其打印出来。

// 1.
File file1 = new File("krb5.conf");
File file2 = new File("producer/krb5.conf");
File file3 = new File("./krb5.conf");
System.out.println(file1.getAbsolutePath());
// Output: C:UsersDocumentsproducerkrb5.conf
System.out.println(file2.getAbsolutePath());
// Output: C:UsersDocumentsproducerproducerkrb5.conf
System.out.println(file3.getAbsolutePath());
// Output: C:UsersDocumentsproducer.krb5.conf   

3。Path一开始可能看起来有点奇怪,但它也可以工作。

C:UsersDocumentsproducer.指向当前目录,因此它本质上与C:UsersDocumentsproducer相同。