0

I need to open a file with a batch file like this:

(right click file.txt) > "open with" file.bat

then I need to get the location of the file.txt and set it to the variable path like this:

set path = <file.txt path>
java test.class path 

How can I set path to the location of file.txt without hardcoding in the path (I will not always know the filename or location)

Tony Cicero
  • 55
  • 1
  • 6
  • not sure if [this](http://stackoverflow.com/questions/28190126/how-can-i-embed-java-code-into-batch-scriptis-it-possible-to-create-java-bat) will help you , but you can take a look. – npocmaka Nov 10 '16 at 16:24
  • 3
    Please do not use a variable named path. It is already an environmental variable that the system uses. Regardless of the file being passed to the batch file at the console, drag and drop or right click sendto, the whole file path is sent to the batch file and becomes an argument to the batch file. `set fpath=%~dp1` – Squashman Nov 10 '16 at 16:31
  • 1
    You could use a [sendTo entry](http://stackoverflow.com/questions/6852833/running-a-batch-script-by-right-clicking-any-file), look here –  Nov 10 '16 at 18:52

1 Answers1

0

Squashman has given in his comment almost every information required for this batch file coding task.

First, don't add spaces around equal sign on assigning a string value to an environment variable. See answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? for a detailed explanation.

Second, don't use names for environment variables which are already predefined by Windows like PATH which is an extremely important predefined environment variable. Open a command prompt window and run set to get output all environment variables predefined for current user account. Details about those variables can be found in Wikipedia article about Windows Environment Variables. Using path as environment variable name results here definitely in an error message on next line because java.* with a file extension defined in environment variable PATHEXT can't be found in current directory or any directory defined in environment variable PATH.

Third, Windows Explorer passes the file(s) selected to the started process on using Send To with full file name (path + file name + file extension) enclosed in double quotes. Run in a command prompt window call /? to get help output on how to reference an argument string of a batch file.

So all you might need in your batch file is:

java.exe test.class "%~dp1"

If you want to see how your batch file is started by Windows Explorer, put at top of your batch file following two commands:

@echo %0 %*
@pause

The first line output by the batch file shows you how Windows Explorer started the batch file via command interpreter cmd.exe.

Community
  • 1
  • 1
Mofi
  • 38,783
  • 14
  • 62
  • 115