0

I would like to check if a java file exists on the PC and if it does, get the path of the file (excluding the filename) and use it in a variable. I need to do this using a batch file.

I have gotten as far as the following command which displays the full path of the .exe file:

for %i in (java.exe) do @echo.   %~$PATH:i

The result being:

C:\Program Files\Common Files\Oracle\Java\javapath\java.exe

However, I'm unable to proceed further, as I need to extract the path, excluding the filename. Alternatively, there might be a command which just returns the path of the folder.

Can someone please help me out?

robinCTS
  • 4,327
  • 4
  • 20
  • 29
  • 1
    `for %i in (java.exe) do (set JAVAPATH=%~$PATH:i) && echo %JAVAPATH:~0,-8%` or simply `for %i in (java.exe) do @echo. %~dp$PATH:i`. – Akina Aug 23 '18 at 12:47
  • Thanks a lot for your reply, let me check and get back to you. – crazy_ashu Aug 24 '18 at 07:54
  • @Akina In my batch file i tried like you said but its giving below error. this is the content in batch file; @ : SET JAVA_HOME="C:\Program Files\Java\jdk1.8.0_121" @ for %i in (java.exe) do (set JAVA_HOME=%~$PATH:i) && echo %JAVA_HOME:~0,-8%......Here i dont know what will be name for java directory thus i want to get it through this command and then i can look for java/javaw.exe.....This is the error message....~$PATH:i) was unexpected at this time. – crazy_ashu Aug 24 '18 at 07:57
  • 1) Check in a command line, not in a batch. 2) Do not forget to quote/duplicate percent signs in a batch. 3) Try second variant I have posted: `for %i in (java.exe) do @echo. %~dp$PATH:i`. – Akina Aug 24 '18 at 09:43
  • @Akina, Thanks for your reply, I had to make this work in batch file. But anyway I have used this link to resolve the issue. https://superuser.com/questions/1148677/finding-location-java-home-in-windows-10 – crazy_ashu Aug 24 '18 at 10:10
  • I used below link to resolve this issue. Thanks. https://superuser.com/questions/1148677/finding-location-java-home-in-windows-10 – crazy_ashu Aug 24 '18 at 10:14
  • Do not forget the PATH value can be altered freely so the result may became wrong or empty. I'd recommend to use some more stable method to find Java path - take it from a registry, for example. – Akina Aug 24 '18 at 10:15
  • @Akina can you please provide some examples so that i can go through the same. – crazy_ashu Aug 24 '18 at 17:46

0 Answers0