Tony Cicero Tony Cicero - 1 year ago 73
Java Question

Open file with batch file, then use file in java class

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)

Answer Source

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 %*

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download