Run as simple perl script in NetBean using Java language - java

I am in the progress of learning perl language.
I have made a simple perl script (as shown as below).
#!/usr/bin/perl
use strict;
use warnings;
print "hi Lala\n";
I am trying to run this script in NetBean using java language.
My code is as below:
public class javaProgram {
public static void main(String[] args) {
Process process;
try
{
String testFile = "perl C:\\Strawberry\\perl_tests\\hello_world.pl";
process = Runtime.getRuntime().exec(testFile);
process.getOutputStream();
process.waitFor();
if(process.exitValue() == 0)
{
System.out.println("Command Successful");
}
else
{
System.out.println("Command Failure");
}
}
catch(Exception e)
{
System.out.println("Exception: "+ e.toString());
}
}
}
But I got this error
Exception: java.io.IOException: Cannot run program "perl C:\Strawberry\perl_tests\hello_world.pl": CreateProcess error=2, The system cannot find the file specified
I have save the script as hello_world.pl in the directory as shown above. So, I am not sure what I am doing wrong.
Is it NetBean problem? The script problem? But when I run the script using Strawberry IDE, there is no problem or errors.

perl is not found.
in your script you are refer to #!/usr/bin/perl wich is not existence in a Windows path. So you have to add the complete path to perl Interpreter.
String testFile = "<path_to_perl>perl C:\\Strawberry\\perl_tests\\hello_world.pl";
Also add the correct path in your perl script:
#!<path_to_perl>perl
use strict;
use warnings;
print "hi Lala\n";

Related

Open Terminal with Java and execute "java -jar"

I'm trying to create an executable .jar that re-opens itself in Mac's Terminal console. (for the sake of having a user interface to enter commands into the program)
// if program is not open in Terminal:
Runtime.getRuntime().exec("java -jar \"" + path + "\" isInConsole");
System.exit(0);
This code executes the command successfully but seamlessly so I don't get the console UI. How can I make it open a visible Terminal window and execute a command in it?
EDIT: I managed to open the Terminal, but still need to figure out how to run the java -jar ... command in it.
This works:
String arg = "cd /Users/potato/Desktop";
Runtime.getRuntime().exec("open -a Terminal --args " + arg);
But this doesn't work:
String arg = "java -jar /Users/potato/Desktop/test.jar isInConsole";
Runtime.getRuntime().exec("open -a Terminal --args " + arg);
For creating processes, class Runtime has been superseded by class ProcessBuilder. A very old but still relevant article regarding class Runtime (because it was published before addition of class ProcessBuilder to JDK) is When runtime.exec() won't and is also relevant for class ProcessBuilder.
As stated in the article, method exec() is not a "shell" and so does not parse the command you give it as a single String parameter. You can help the method with parsing by providing an array of Strings.
I suggest you read the article and also the javadoc for class java.lang.ProcessBuilder.
The code I ended up using executes some AppleScript code: (as DanielPryden suggested)
public static void main(String[] args){
if(args.length == 0 && System.getProperty("os.name").toLowerCase().contains("mac")){
try {
String path = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();
String command = "tell application \"Terminal\"\n" +
"do script \"java -jar \'" + path + "\' isInConsole\"\n" +
"close the front window\n" + // because "do script..." opens another window
"activate\n" +
"end tell";
String[] arguments = new String[]{"osascript", "-e", command};
Runtime.getRuntime().exec(arguments);
System.exit(0);
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// program continues...
}

error with starting cmd in windows using java?

The following method starts the cmd in Windows and it takes a parameter of the command which need to be run.
I have tested this method using the following commands: net users and it worked fine and it printed the users accounts. but if I run the dir command I get the following error:
java.io.IOEXception:
Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified (in java.lang.ProcessBuilder)
Code :
private String commandOutPut;
public void startCommandLine(String s) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(s); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String commandOutPut;
while ((commandOutPut = br.readLine()) != null) {
this.commandOutPut = this.commandOutPut + "\n" + commandOutPut;
}
System.out.println(this.commandOutPut);
}
Well, obviously, your method does not start cmd. How did you get this notion?
The net command is a standalone command so it runs just fine, but the dir command is not standalone, it is an internal command of cmd.exe, so you cannot run it without launching cmd.exe to execute it.
To get it to work you will have to pass not dir but cmd.exe /c dir or something like that.
Don't know if this perception can help you. But, seems that "net users" are recognized as Windows command, since "Execute" dialog can run it.
But, for some reason, the "dir" command aren't. When try to run, Windows responds that command was not found.
Additionaly, I tried run Command with inline arguments too, but the arguments are simply ignored. (sorry for bad english)
My best guess is that this is because "net" is a real executable (there is a file WINDIR\System32\net.exe"), while "dir" is a builtin command of the command interpreter - it has no executable and is directly executed within cmd.exe.
Howevever you may get around this be invoking "dir" command inside the cmd process. The syntax - as per Microsoft docs - is:
cmd /c dir
There are also some related answers on the site:
How to execute cmd commands via Java
Run cmd commands through java
You can use the following code for this
import java.io.*;
public class demo
{
public static void main(String args[])
{
try
{
Process pro=Runtime.getRuntime().exec("cmd /c dir");
pro.waitFor();
BufferedReader redr=new BufferedReader(
new InputStreamReader(pro.getInputStream())
);
String ln;
while((ln = redr.readLine()) != null)
{
System.out.println(ln);
}
}
catch(Exception e) {}
System.out.println("Done");
}
}

Java - Command Execution in Runtime

I tried out a simple program to execute Linux command at run time. But the following program gets compiled and runs without any error, but the text file is not getting created as intended.Is there anything wrong in this program?
import java.io.*;
class ExecuteJava
{
public static void main(String args[])
{
String historycmd = "cat ~/.bash_history >> Documents/history.txt";
try
{
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(historycmd);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Try accessing some of the functions Process provides. I'd start with exitValue. Typically a -1 indicates something went wrong while a 0 means nothing especially bad happened.
Also try InputStream and Error Stream, and read them fully. See if either has useful feedback for you.
Other than that, try what andy256 suggests in comments. Ensure the Documents directory exists in the executing directory of the program.
The append operator >> is meant to be interpreted as part of the command shell. Use
String[] historycmd =
{ "bash", "-c", "cat ~/.bash_history >> Documents/history.txt"};

Having trouble starting a program with the Runtime.getRuntime().exec(command)

I'm currently writing a Java program that can open .exe programs on my PC, like MS Word for example.
I am having a problem though, because Runtime.getRuntime().exec() will only successfully open certain programs. I have used the exact same code for all the programs, but regardless, some programs won't open.
Here is my code for a program I downloaded, Picasa 3:
class picasaHandler implements ActionListener
{
public void actionPerformed(ActionEvent r)
{
try
{
Runtime.getRuntime().exec("cmd /c start Picasa3.exe");
}
catch (IOException t)
{
JOptionPane.showMessageDialog(null,
"Sorry, could not find Picasa 3");
}
}
}
So my question is, why won't Runtime.getRuntime().exec() run all the programs I use it on, and how do I run programs like Picasa 3, that I cannot run at this moment with this method.
I'm guessing that Picasa3.exe is not on your %PATH% anywhere so it doesn't know how to load it. Have you tried specifying the full path to Picasa3.exe?
Runtime.getRuntime().exec("cmd /c \"c:\\program files (x86)\\Google\\Picasa3\\Picasa3.exe\"")
File file=new File("picassa3");
String filename=file.getAbsolutePath(file);
try
{
Runtime.getRuntime().exec(filename);
}
catch (IOException t)
{
JOptionPane.showMessageDialog(null,
"Sorry, could not find the file");
}
Runtime's exec can only start applications that are on the Windows path. Some programs are automatically on the path, while others, like Picasa, is not.
The only work-around for this is to determine the correct path and then launch that application.
This might work for you.
If you want to run a certain program using Runtime.exec(), just add it's installation path to path variable in your System Variables. To find it's installation path, simply right click on it's shortcut and select "Find Target". Then concat that entire address at the end of your path Variable.

Shell script not running R (Rhipe) program from Java code

I have a simple shell script which looks like this:
R --vanilla<myMRjob.R
hadoop fs -get /output_03/ /home/user/Desktop/hdfs_output/
This shell script runs myMRjob.R, and gets the output from hdfs to local file system. It executes fine from terminal.
When i am trying to run shell script from java code, i am unable to launch the MapReduce job i.e. the first line isn't getting executed. While "hadoop fs -get .." line is running fine through Java code.
Java code which i used is:
import java.io.*;
public class Dtry {
public static void main(String[] args) {
File wd = new File("/home/dipesh/");
System.out.println("Working Directory: " +wd);
Process proc = null;
try {
proc = Runtime.getRuntime().exec("./Recomm.sh", null, wd);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The reason behind this whole exercise is that i want to trigger and display the result of the myMRjob.R in JSP.
Please help!
The reason your shell script isn't running from the exec call is because shell scripts are really just text files and they aren't native executables. It is the shell (Bash) that knows how to interpret them. The exec call is expecting to find a native executable binary.
Adjust your Java like this in order to call the shell and have it run your script:
proc = Runtime.getRuntime().exec("/bin/bash Recomm.sh", null, wd);
When you called hadoop directly from Java, it is a native executable and that's why it worked.

Categories