0

I am facing a weird problem, I have a Java program which calls a shell script in netbeans. The shell script is supposed to create a file in the same directory where the script is running. But in this case the output file is getting created in netbeans (workflow) folder.

can anyone let me know where am i going wrong. I cant change the script as it is dynamic.

Note: If i run the class on command prompt the file is created in script directory itself, problem is when i run in netbeans

Appreciate any help

1
  • Would you mind posting the problematic code? Sounds like a problem with relative pathnames to me. Commented May 24, 2014 at 7:18

2 Answers 2

1

Use ProcessBuilder and invoke directory(File) to set the appropriate working directory.

Sign up to request clarification or add additional context in comments.

Comments

0

Consider the following script:

#!/bin/sh
echo "hi" > hello.txt

When this script is run, it will create the "hello.txt" file in the current directory.

So what is the current directory? Well it depends on how you run the script.

  • If you just run the script from the shell prompt, then the current directory will be the shell's current directory; i.e. where you cd'd to.

  • If you run a Java program and it uses Runtime.exec() to run the script, then the script's current directory will be the Java program's current directory.

  • When a Java program is launched from the shell command prompt (e.g. java -cp ... SomeClass) then its current directory will be the shell current directory.

  • When you launch a Java program from an IDE, then the Java program's current directory is determined by the IDE Java launcher. It is common for IDEs (e.g. NetBeans, Eclipse) to make the project directory the current directory for the launched Java program.


So that's what is happening. What should you do about it?

  • As Tim Bender suggests, you could use ProcessBuilder, and set the current directory for the child process to directory that you want. But that means that your Java program needs to know what the right directory is.

  • You could change the script to use an absolute pathname for the output file. But that means that the right directory has to be "wired" into the script.

  • The best solution (IMO) is to leave the Java program and the script alone, and change the IDE's Java launcher configuration to make the current directory of the launched program something more appropriate (for testing).

  • Alternatively, make the output directory a command line argument (or config file entry) for the Java program ... and have it pass the argument value to the shell script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.