0

In a piece of some Gradle code I want to get a current folder name without splitting the path. But all attempts that I tried:

Paths.get(".").getFileName()
new File(".").getName()
new File(".").name

, return a dot "." instead of the name. Is there some function that gives the name, not another string by which the folder could be addressed?

What is interesting, if I use:

    String currentDirPath = new File(".").absolutePath
    println currentDirPath
    currentDirPath = currentDirPath.substring(0,currentDirPath.lastIndexOf("\\"))
    println currentDirPath
    String currentDir = currentDirPath.substring(currentDirPath.lastIndexOf("\\")+1)

, it is seen, that the path string looks as:

C:\Users\543829657\workspace\dev.appl.ib.cbl\application\.

So, it is simply incorrect to take the last substring after '\'. But all those three functions take not the name of the name of the really actual folder, but the last "."!

Gangnus
  • 24,044
  • 16
  • 90
  • 149

3 Answers3

3

Gradle is build upon Groovy, which is a JVM language, just like Java. So to get the current working directory, you can simply use the same ways you would use in Java. As an example, the following code will give you the name of the working directory, not the full path (check Frans answer).

new File('').absoluteFile.name

However, please mention that, in Gradle, you should not create or access files from the current working directory, but from the project (project.projectDir) or build (project.buildDir) directories, since you might accidentally build projects from lower directories, e.g. because Gradle checks for settings.gradle scripts in parent directories.

Lukas Körfer
  • 13,515
  • 7
  • 46
  • 62
  • Excellent! Right the correct function combination, and also a very useful additional piece of info. I was launching the task FROM child directory and wanted to run it from there. I did not know it is not supposed way of work. – Gangnus Jul 19 '17 at 10:09
  • That folder name I need anyway - for check that the task was called from the correct folder. If not, it would create a heap of troubles. It is a pity I cannot give you two votes. – Gangnus Jul 19 '17 at 10:13
0

Is not

new File("").absolutePath

what you are looking for?

Fran García
  • 2,011
  • 16
  • 24
  • I am looking for name, not the whole path, definitely. I have already a working piece cutting the appropriate substring out of absolute path. But I cannot believe the only way is so awkward. – Gangnus Jul 19 '17 at 09:58
0

We should not really retrieve the absolute path that way.

In Gradle, you can use project.projectDir to get the project path or rootProject if its a multiproject or if you want to get a path of the file project.file('yourfile')

LazerBanana
  • 6,865
  • 3
  • 28
  • 47