简体   繁体   English

如何在不指定驱动器的情况下在“ src”(源)目录中创建文件

[英]How to create file in 'src' (source) directory without specifing the drive

I know how to create file in Java with a specific path. 我知道如何在Java中使用特定路径创建文件。
I want to create file in the source folder of the project without specifing the drive because it can change from PC to PC. 我想在项目的源文件夹中创建文件而不指定驱动器,因为它可以在PC到PC之间更改。

I tried to use: 我尝试使用:

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

with dot before the 'src': 在“ src”之前加点:

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

with \\\\ : \\\\

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

It doesn't work, it throws exception. 它不起作用,它引发异常。

This one works but creates it on my Apache server folder: 这个可以工作,但是会在我的Apache服务器文件夹中创建它:

File targetFile = new File("uploadedFile.xml");
targetFile.createNewFile();

This is the hierarchy: 这是层次结构:
在此处输入图片说明

The code runs on the LoadGameServlet.java 该代码在LoadGameServlet.java上运行

您甚至可以在创建实际文件之前,使用诸如System.out.println(targetFile.getAbsolutePath())的工具调试将在何处创建文件。

After searching alot I found a way to do it. 搜索了很多之后,我找到了一种方法。

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

I checked it and it works fine. 我检查了一下,效果很好。

Thanks for your help. 谢谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM