简体   繁体   中英

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

I know how to create file in Java with a specific path.
I want to create file in the source folder of the project without specifing the drive because it can change from PC to PC.

I tried to use:

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

with dot before the '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:

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

This is the hierarchy:
在此处输入图片说明

The code runs on the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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