Java 如何在';src&x27;(源)目录,但不指定驱动器

Java 如何在';src&x27;(源)目录,但不指定驱动器,java,jakarta-ee,servlets,src,Java,Jakarta Ee,Servlets,Src,我知道如何用Java创建具有特定路径的文件。 我想在项目的源文件夹中创建文件,但不指定驱动器,因为它可以从一台PC更改到另一台PC 我尝试使用: File targetFile = new File("/src/SavedGames/uploadedFile.xml"); targetFile.createNewFile(); 在“src”前面加上点: File targetFile = new File("./src/SavedGames/uploadedFil

我知道如何用Java创建具有特定路径的文件。
我想在项目的源文件夹中创建文件,但不指定驱动器,因为它可以从一台PC更改到另一台PC

我尝试使用:

File targetFile = new File("/src/SavedGames/uploadedFile.xml");
targetFile.createNewFile();
在“src”前面加上点:

File targetFile = new File("./src/SavedGames/uploadedFile.xml");
targetFile.createNewFile();
使用
\\

File targetFile = new File("\\src\\SavedGames\\uploadedFile.xml");
targetFile.createNewFile();
它不工作,它抛出异常

这一个可以工作,但会在我的Apache服务器文件夹中创建它:

File targetFile = new File("uploadedFile.xml");
targetFile.createNewFile();
这是层次结构:


代码在LoadGameServlet.java上运行,甚至在创建实际文件之前,您可以使用类似于
System.out.println(targetFile.getAbsolutePath())
的工具来调试文件的创建位置

经过多次搜索,我找到了一种方法

File targetFile = new File(new File(LoadGameServlet.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent() + "\\uploadedFile.xml");
String decoderPath = java.net.URLDecoder.decode(targetFile.getPath(), "UTF-8");
String newPath = decoderPath .replaceAll("build\\\\web\\\\WEB-INF\\\\classes\\\\Servlets", "src\\\\java\\\\SavedGames");
targetFile = new File(newPath);
targetFile.createNewFile();
我检查过了,效果很好


感谢您的帮助。

您是否尝试过
src/SavedGames/uploadedFile.xml
?现在检查:它尝试在c:\myApacheServer\bin\src\SavedGames\SavedGames
src/SavedGames/iploadedFile.xml
上创建。如果
src/SavedGames/iploadedFile.xml
不起作用,请检查mainfest.mfest中的
类路径
,以确保它指向项目的根目录。请参阅@SualehFatehi,这个解决方案对我不起作用。我尝试了这个解决方案:URL path=Thread.currentThread().getContextClassLoader().getResource(“src/SavedGames/”);但是它仍然在apache服务器上创建它好主意,它在C:\src\SavedGames上创建它-没有这样的目录。然后应该先创建文件夹,或者使用
.mkdirs()
函数以编程方式创建它。但是我不想在“C:'驱动器上创建它,因为可能用户已经有这样的文件夹。我想在我的服务器SavedGames包上创建它。运行时,您当前的文件夹似乎是Apache文件夹,因此所有相对路径(如“src/”或“/src/”)都是相对于该文件夹的。您应该确保使用“.”和相对文件夹的正确组合将文件指向所需的位置。此外,如果在文件夹名称中使用“.”,还可以使用方法
targetFile.getCanonicalPath()
来解析文件将存储到的确切位置。