簡體   English   中英

如何在不指定驅動器的情況下在“ src”(源)目錄中創建文件

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

我知道如何在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();

我檢查了一下,效果很好。

謝謝你的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM