Matthew Pieper
Matthew Pieper

Reputation: 11

Reading cd of cmd from within java command-line application

I am making my own programming language called "Mast" in java for my study. I made a compiler called "cmpmast" that works similarly to javac and gcc in that it is a command-line application.

I compiled the java project for this compiler to a .exe file and put it in folder that I added to PATH (windows 10). Everything seems to work fine except for finding the input files: say we have a folder like "C:\users\me\desktop\folder" which contains the empty file "hello.mast". when I open the cmd, change the directory to that folder and execute the command C:\users\me\desktop\folder>cmpmast hello.mast, the program is unable to find the file.

After some debugging, I found out that it is not looking inside the cd of the cmd but inside the folder in which I put the cmpmast.exe file.

To find a file, I simply used the java.io.File class like so: File inputFile = new File(pathname); where pathname is the argument passed to my compiler (cmpmast).

How would I get the cd of the system console (cmd) I am running my compiler in, from inside the java program? I assume this to be possible since all command-line compilers I have used worked like this.

I already tried to use System.getProperty("user.dir") and it resulted in the same unwanted path.

Upvotes: 0

Views: 106

Answers (2)

rzwitserloot
rzwitserloot

Reputation: 102814

You're doing it: new File("hello.mast"); is how you do it.

The fact that it's not working for you means that whatever tool you used to make an exe file is going out of its way to change the current working directory of your process to the dir that the exe is in. It is presumably doing this to let you access resources there, which is misguided (you can use j.l.Class's getResource mechanism for this).

Given that it does this, it is not possible to recover the working dir you were at.

Hunt around the tool that made the exe for you (launch4j, perhaps), find the option to turn off the 'change working directory' setting. If it isn't there, your exe cannot do what you want here.

Upvotes: 1

paulsm4
paulsm4

Reputation: 121599

SUGGESTION:

  1. Please don't mess with "converting to .exe". It's probably unnecessary for this project.

  2. Instead, just write a simple .bat file:

    a) Set %PATH% and %JAVA_HOME% for your JRE (both might be optional)

    b) "cd" to your app install dir (wherever it happens to be installed)

    c) Invoke the app (and leave it running in the cmd console window)

  3. Create a desktop shortcut to your .bat file

Voila! Done!

Upvotes: 1

Related Questions