1

I have a Java application that produces an output which is stored in a myfile.txt file using batch script. Now I would like to pass the absolute path of this myfile.txt file to another java application as a command line argument.

So something like:

java -jar "path/to/jar/MyJar.jar" > myfile.txt

<Something to get and store absolute path of myfile.txt>

java -jar "path/to/jar/MyOtherJar.jar" <absolute path of myfile.txt>

Now I found this answer which states the use of %~dpnx1 but I can't understand how to apply this. Any suggestions?

hw-135
  • 162
  • 1
  • 15
  • If you are creating a file in current directory then you can use $PWD to get the current direct path. Then you just have to concatenate file name with that. – Hans Jun 17 '19 at 16:54
  • The `MyOtherJar` file is in a separate directory. It is not in the same directory as `myfile.txt`. – hw-135 Jun 17 '19 at 17:21

1 Answers1

1

The use of the %~dpnx1 or simply %~f1 syntax requires that the filename is in the arguments.
dpnx=(D)rive (P)ath (N)ame e(X)tension = Full(F)ilename

That can be done via CALL :func <argument> or via FOR.

call :getAbsolutePath resultVar "myFile.txt"
echo %resultVar%
exit /b


:getAbsolutePath <returnVar> <filename>
set "%1=%~f2"
exit /b

Or via FOR

FOR /F "delims=" %%X in ("myFile.txt") DO set "absPath=%%~fX"
jeb
  • 78,592
  • 17
  • 171
  • 225
  • This works fine. Can you please tell me what is the use of `%%~fX` here? Also, is there any way I can avoid generating this `myfile.txt` and directly pass the output of `MyJar` to `MyOtherJar`? I was doing it this way because I am not very familiar with the syntax. If there is a way of eliminating this extra file generation step? – hw-135 Jun 17 '19 at 17:44
  • `%%~fX` uses the `FOR` parameter `%%X` with the modifier `~f` to get the absolute filename. – jeb Jun 17 '19 at 17:52
  • @jackw To avoid your temporary file, probably a pipe could work `java -jar "path/to/jar/MyJar.jar" | java -jar "path/to/jar/MyOtherJar.jar"` but if it works depends on the jar files – jeb Jun 17 '19 at 17:53
  • Why are you using a `for /F` loop although a standard `for` loop would suffice? – aschipfl Jun 17 '19 at 21:28
  • @aschipfl There is no explicit reason, it's only a habit – jeb Jun 18 '19 at 06:07