简体   繁体   中英

How do i get root project directory of Intellij during runtime execution

I am trying to code out an import function that imports certain content of file into intellij. I would like to specify the default path of this file as one of the directories under my content root. I would want to know if intellij provides a specific function call to get the content root during runtime? Since i will not be able to hardcode the file path as they differ for different computers.

For example under my content root directory called "main", I have a "data" folder which i want to use as my directory for importing files inside that folder.

IntelliJ IDEA run configuration working directory defaults to the project root. Even if you change it, its path will be stored relatively in the project so that it can work on any system.

Sample code to get the path of the data directory that resides under the current working directory:

package com.jetbrains.support;

import java.io.File;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    File directory = new File("./data");
    System.out.println(directory.getCanonicalPath());
  }
}

To get the working directory (project root) path without the data subdirectory you can use this code:

File directory = new File("./").getCanonicalPath();

Proof of work:

证明

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