Jess
Jess

Reputation: 3725

Get module path not root path in Java

I have a multi-module Java(Spring) project, which build by Gradle 6.7.1. And I use in Jetbrain IDEA to develop. The file Structure like this:

root
  |--orm
  |   +---hibernates
  |
  |--web
      |--mvc
      |--rest

And then, I have tried some codes in my module project like below, what I get all are root path (/home/user/IdeaProjects/root/), not module path (/home/user/IdeaProjects/root/web/mvc). How can I get module path (/home/user/IdeaProjects/root/web/mvc) ?

new File("").getAbsolutePath()

Upvotes: 0

Views: 933

Answers (2)

Jess
Jess

Reputation: 3725

based on the answer of @ToYonos. We can do that by this:

  1. settings.gradle gets the project path of every module.
  2. write a key value into the info.properties in every module.
  3. Spring Project read this properties file.

Code

Because struct of my project is:
root
  |--orm
  |   +---mybatis
  |   +---jpa
  |   +---...
  |--web
      +--mvc
      +--rest
      +--...

So, I should loop twice to get the module name. And I exclude project without build.gradle.

file("${rootDir}").eachDir {
    it.eachDirMatch(~/.*/) {
        if (it.list().contains("build.gradle")) {
            def moduleName = "${it.parentFile.name}:${it.name}"
            println "   ${moduleName}"
            include moduleName
}}}

And then, read and write info.properties.

import java.nio.file.Paths

// read
def project_dir = project(":${moduleName}").projectDir
def propFile = Paths.get("${project_dir}", "src", "main","resources","info.properties").toFile()
propFile.createNewFile()
Properties props = new Properties()
propFile.withInputStream {
    props.load(it)
}

// write
props.setProperty("project.dir","$project_dir")
props.store propFile.newWriter(), null

Upvotes: 0

ToYonos
ToYonos

Reputation: 16833

Assuming for instance that your mvc project is setup like this in setting.gradle, in the root folder :

include 'mvc'
project(':mvc').projectDir = new File('./web/mvc')

Then, to get the path /home/user/IdeaProjects/root/web/mvc, just try this :

println project(':mvc').projectDir

Will prints :

/home/user/IdeaProjects/root/web/mvc

Upvotes: 1

Related Questions