I am building a GUI in Java (Swing) and I have to execute Java code from that. For the sake of testing simple code like printing HelloWorld in Java will be ok.
I have seen the forum questions and I just know that I have to invoke Operating System (I am using Windows7) to execute that compilation task.
Thank you.
P.S: I have tried with Runtime.getRuntime().exec() command but no success.
If you are using IDE you don't need to call these commands.
Compile:
javac HelloWorldSwing.java
Run:
java HelloWorldSwing
....
If you want to use Runtime.getRuntime().exec(). Here is an example of using Runtime.getRuntime().exec()..
import java.io.*;
public class TestExec {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
"This just runs the dir command, captures its ouput and copies it to the programs stdout. Not very exciting but it shows the basic parts to use Runtime.exec(). You can also open up the process' output and error streams. "
so you can send commands with Runtime.getRuntime().exec(), you can use javac or java commands that i have wrote above.
you might want to check out the java compiler api for the compiling code part,
runtime.exec() should work with the correct commands to launch the app.
There is an example of using the JavaCompiler API in the SSCCE Text Based Compiler (STBC). Be sure to read the pages related to getting a tools.jar on the run-time class-path.
The STBC is open source.
For compiling you need an installed JDK which includes the Java compiler javac. You can call javac using via Runtime.getRuntime().exec() for compiling Java source code and then load it.
Alternatively you can use the Java Compiler API. The main compiler API can be retrieved via javax.tools.ToolProvider.getSystemJavaCompiler();
See also this article: The Java 6.0 Compiler API
Related
I am using a jar to run some code as a helper for a program (OSX). I want to open this jar programmatically, and have been using a ProcessBuilder to run it through the terminal.
However, I want to give the jar some arguments (specifically a file location, but that's irrelevant). I have using java -jar jarName arg, but this doesn't work with people who don't have Java tools installed.
I have tried to use open jarName --args arg, but the jar doesn't recognize the args.
As a test, I am just using the following code for now.
public static void main(String[] args) {
try {
// set a PrintStream to see the args presented
System.setOut(
new PrintStream(new FileOutputStream(new File(System.getProperty("user.home") + "/Desktop/argsTest.txt"))));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(argsSize: "+args.length");
for (String s : args)
System.out.println(s);
}
I am fine with trying other methods of opening jars, so long as they are available on all up to date systems.
I have the JRE packaged in the application, is there a way to use that?
Bundle jre with with your program. Refer to Bundle JRE along with executable jar
or if you are using netbeans - it will allow you to test it first. https://netbeans.org/kb/docs/java/native_pkg.html
how to run - https://netbeans.org/kb/docs/java/native_pkg.html#check
Welcome on StackOverFlow!
Sadly, the answer is no, you can't do this. If you want to run some java code, from a jar or not, you will need to have java installed on the machine. Specifically, you need the JRE to have the JVM.
But you can provide java by your own when deploying your app. See this threads:
https://superuser.com/questions/745112/how-do-i-run-a-jar-file-without-installing-java
Running java without installing jre?
for more informations.
I'm trying to run a Python script from a Java program using Process and ProcessBuilder, however Java keeps using the wrong version of Python. (The script needs 3.6.3 to run and Java runs Python 2.7)
However when I run the script from the terminal (outside of Java), it runs the correct Python (3.6.3). How does one change what version of Python gets run when called by Java?
The short version is it changes with your PATH environment variable.
Under Windows, Technet has the answer. Scroll down to the 'Command Search Sequence' section. This answer explains it nicely.
For UNIX-like OS's, this answer is nicely detailed.
There are two very useful commands for determining which executable is going to be called: which for UNIX-likes and where for newer Windows.
The most likely reason for the difference between Java and the terminal is a difference in your PATH. Perhaps your Java version is being run with a modified PATH? A launch script of some kind may be changing it.
Add /usr/bin/python3.4 to the start of your command to force the version of python you want. If you're not sure where python is installed, have a go at using whereis python and seeing what you get back.
private int executeScript(final List<String> command) {
try {
final ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/python3.4").command(command);
processBuilder.redirectErrorStream(true);
System.out.println("executing: " + processBuilder.command().toString());
final Process process = processBuilder.start();
final InputStream inputStream = process.getInputStream();
final InputStream errorStream = process.getErrorStream();
readStream(inputStream);
readStream(errorStream);
return process.waitFor();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return -1;
}
Then just pass in the List containing your python commands.
I got this error messaje while trying to copile a simple Java program. I know there is this question already here on Stack but the solution(that i forgot to include the .java suffixwhen compiling the program) still doesn't work for me. This is the program:
import java.io.Console;
public class Introductions {
public static void main(String[] args) {
Console console = System.console();
// Welcome to the Introductions program! Your code goes below here
String firstName = "Paul";
console.printf("Hello, my name is %s\n", firstName);
console.printf("%s this is learning how to write Java\n", firstName);
}
}
There are two different commands to compile Java programs and run Java programs. You're receiving an error that means that the command to compile the program (javac) has received arguments that don't include the .java suffix, as mentioned in other questions about this error.
It sounds, however, like you are compiling correctly, using javac Introductions.java. Your problem is actually in the second step, running the program. Running javac Introductions tells Java you want to compile again, and so it correctly points out that you forgot the extension.
But you're not wanting to compile a second time; you want to run it! That uses java instead of javac.
To compile: javac Introductions.java
To run: java Introductions
See also How do I run a Java program from the command line on Windows? (though this isn't really Windows-specific).
There is a Java demo :
package com.demo;
public class Demo {
public static void main(String[] args) {
System.out.println("hello world!");
}
}
How can I use shell to transfer it?
I am not very familiar with Linux. There is a demand:use shell to transfer java method.
Please tell me or give me a demo.
If by transfer you meant run (or execute), then simply do (you have to be in folder where Demo.class, compiled version, is)
java com.demo.Demo
but you have to have java on path, so test that first running
java -version
from console...
Or you can specify absolute path to java program....
You can write the same command into hello.sh if you want, there is not a big difference to have the command in script or execute it from command line.
If your script has to be more general, you should look for Linux scripting: Passing parameters and so on...
This question already has answers here:
How to run Unix shell script from Java code?
(17 answers)
Closed 7 years ago.
I'm trying to execute a shell script from Java.The script is supposed to download the file from the URL using wget.Here goes my code.
public class RunShellScriptFromJava {
public static void main(String a[]) {
try {
ProcessBuilder pb = new ProcessBuilder("/bin/sh","script.sh");
Process p = pb.start();
p.waitFor();
System.out.println("Success");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Content of script.sh
echo "start"
wget http://alex.smola.org/drafts/thebook.pdf
echo "end"
My Question:
Is this the right way doing it?If not please point me in the right direction.It doesn't throw any exception but I see that the file is not getting downloaded.Any lead/help is appreciated.
Thanks.
PS:I have given execute permission for the script
The code sample in the question lacks error handling around the usage of ProcessBuilder, so it's likely that some kind of error happened, but you aren't getting visibility into it.
The return code of Process#waitFor is being ignored. The returned value is the exit code of the spawned process. I recommend checking to see if this value is non-zero.
There is also no handling of stdout or stderr, so you won't know if the spawned process is writing any output that explains what happened. You can access stdout and stderr by using Process#getInputStream and Process#getErrorStream respectively.
Note also that it is possible for your process to hang if it fails to fully consume the streams, or at least redirect them. I've noticed this problem is particularly common on Windows. A standard technique is to spawn background threads to consume the streams. This previous question discusses that technique and others.
Java ProcessBuilder: Resultant Process Hangs
After the error handling in the Java code is enhanced like this, I expect you'll have a better chance of diagnosing what went wrong with the script.
The right way to do this is to use Java to download the file instead of the shell script. The problem with shell scripts is that they are system dependent. By using them you lose one of the main benefits of java which is system independence. There are a number of libraries in Java that will accomplish that functionality. The following will work for you using the FileUtils class from apache IO Commons.
URL url = new URL("http://alex.smola.org/drafts/thebook.pdf");
File download = new File('.');
FileUtils.copyURLToFile(url, download);
This script and java example works, perhaps specify the full path to wget to ensure you know where the pdf is being saved.
$ javac RunShellScriptFromJava.java
$ java RunShellScriptFromJava
Success
$ ls
RunShellScriptFromJava.java thebook.pdf RunShellScriptFromJava.class script.sh
Example/updated script:
wget -O /home/MYSER/test.pdf http://alex.smola.org/drafts/thebook.pdf