1

I have a shell script which I'm trying to call from Java. The shell script contains:

cat /dev/tty.USB0 > file.txt

In my Java code I am using:

Process p= Runtime.getRuntime().exec("/home/myname/Scrivania/capture.sh");

But it does not work. When I run it from the terminal it works as expected.

AlBlue
  • 23,254
  • 14
  • 71
  • 91
biomaucal
  • 13
  • 4
  • 1
    Possible duplicate of [How to run Unix shell script from java code?](http://stackoverflow.com/questions/525212/how-to-run-unix-shell-script-from-java-code) – Ani Menon May 01 '16 at 10:00

3 Answers3

2

You can't directly execute a .sh script like this, since it's not an executable. Instead, you have to run /bin/sh -c /home/myname/Scrivania/capture.sh instead.

AlBlue
  • 23,254
  • 14
  • 71
  • 91
1

First of all, it's not a good style to work with OS-based features in Java code. Instead of that i suggest you to work with system input/output streams only. For example if your program should handle output of your script, you can do something like:

cat /dev/tty.USB0 > java YourMainClass 

and then work directly with System.in.

Even if your program is more complicated than script output consumer, you can rewrite it to remove all OS-based parts from your program, it'll make your code more stable and maintainable.

Everv0id
  • 1,862
  • 3
  • 25
  • 47
0

What you are doing works. Well, it should.

My guess as to what is/seems wrong is this: You might be looking for the output file "file.txt" in the wrong place.

Here's a little experiment

System.out.println("Output file - " + new File("file.txt"));
Process p= Runtime.getRuntime().exec("/home/myname/Scrivania/capture.sh");

The first line should tell you where to look for your file.

P.S. Of course, do remember to import java.io.File :)

Emmanuel
  • 322
  • 2
  • 12