![](/img/trans.png)
[英]Where should the git directory be in a IntelliJ IDEA file hierarchy?
[英]IntelliJ IDEA new File(…) uses Workspace directory as root instead of git repository directory
我剛從Eclipse Luna遷移到IntelliJ IDEA 14.0.3,但在為資源創建新的File(...)對象時遇到問題。 這是我的設置:
\dev\git\myproject\src\main\resources\myfile.txt is the resource I want to read
\dev\idea\workspace\myproject contains my IDEA project
這意味着我在一個目錄中創建了一個IDEA項目,並導入了我的(maven)項目,該項目駐留在我的git存儲庫目錄中。 現在,當我使用以下語句創建新的File對象時
inputFile = new File("src/main/resources/myfile.txt");
這將導致以下路徑:
\dev\idea\workspace\myproject\src\main\resources\myfile.txt
但是,我想從中檢索資源
\dev\git\myproject\src\main\resources\myfile.txt
Eclipse曾經用來正確設置目錄,但是如何用IDEA實現呢?
問題不在於IntelliJ,而在於您嘗試訪問文件的方式。
從您的問題中,我可以看到您使用了maven,並且在src / main / resources中有一個文件想要訪問。
按照Maven,當您在src / main / resources中有一個文件時,這也意味着該文件也將在classpath中可用(請參閱Maven文件夾結構以了解更多信息)。
但是,您嘗試使用相對路徑(包括maven文件夾結構)訪問文件,並且在打包項目時此代碼將不起作用。 由於maven將排除jar / war / ejb或任何其他軟件包中的文件夾(src / / ),僅包含資源。
您應該嘗試從classpath訪問文件,這是正確的方法,最重要的是,即使打包了程序,它也可以工作。
嘗試將代碼替換為
inputFile = new File(this.getClass().getClassLoader().getResource("myfile.txt").getFile());
要么
inputFile = new File(Thread.currentThread().getContextClassLoader().getResource("myfile.txt").getFile());
根據項目類型(獨立或網絡應用)使用以上代碼段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.