I'm trying toopen/execute another program, which is a .jar file, but I'm getting the following error:
it is not a windows application
(java.io.IOException: CreateProcess error=193)
Here is my code:
import java.io.IOException;
public class Test8 {
public static void main(String[] args) {
try {
String filepath = "C://Users//Alex//Desktop//Speedtest.jar";
Process p = Runtime.getRuntime().exec(filepath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
At the command-line, JARs are executed with java -jar. Try passing a String array:
String[] args = new String[] {"java", "-jar", "/path/to/myJar.jar"};
Process p = Runtime.getRuntime().exec(args);
Related
I have a Java class called InputTxt and it has an int attribute id. I want to write a shell script that creates a file with id as the file name.
NOTE: The java function that calls this script returns something other than the id.
Just pass the id as a parameter to the script:
import java.io.*;
class InputTxt {
static int id;
public static void main (String[] args) throws IOException {
id = args.length;
try {
Process p = Runtime.getRuntime().exec(
new String[]{"touch", Integer.toString(id)});
} catch (IOException e) {
throw e;
}
}
}
Sample run:
$ javac InputTxt.java
$ java InputTxt 4 5 6
$ ls
3 InputTxt.class InputTxt.java
I am trying to run maven command from java main but it is not working for me as desired.
When i run the below code it runs the maven command on the same existing project in which this main class residing, but i want to run this maven command from this class to any another project folder.
Please help!
Thanks in advance!
package com.codecoverage.runner;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MavenCoberturaRunner {
public static void main(String[] args) throws IOException, InterruptedException {
Process p = null;
try {
p = Runtime.getRuntime().exec("C:/apache-maven-2.0.9/apache-maven-2.0.9/bin/mvn.bat clean cobertura:cobertura -Dcobertura.report.format=xml");
} catch (IOException e) {
System.err.println("Error on exec() method");
e.printStackTrace();
}
copy(p.getInputStream(), System.out);
p.waitFor();
}
static void copy(InputStream in, OutputStream out) throws IOException {
while (true) {
int c = in.read();
if (c == -1)
break;
out.write((char) c);
}
}
}
You should use Runtime.exec(String command, String[] envp, File dir) method,
which executes the specified string command in a separate process with the specified environment and working directory.
What you want is to set working directory so it points to the place you need to run Maven at.
use -f in command line
C:/apache-maven-2.0.9/apache-maven-2.0.9/bin/mvn.bat -f path/to/your/pom.xml clean cobertura:cobertura -Dcobertura.report.format=xml
I have the following code segment to run a bat file:
String workingDir = System.getProperty("user.dir");
ProcessBuilder pb = new ProcessBuilder("cmd", "/c",
"\"" + workingDir + File.separator + "midl.bat\"");
Process ddsBuildProc = pb.start();
ddsBuildProc.waitFor();
The workingDir includes spaces in the path. Eventhough I use quotes to enclose the workingDir+fileName string, the shell still splits the workingDir and doesn't run the bat file. If a try and copy-paste-execute the bat file path string in the Windows command window manually, it works as expected. What can be the problem here?
Also, please do not close this question as duplicate because I tried all the solutions in the other questions with no success.
Don't quote commands in a command list, unless the command been executed expects it, this will just stuff things up
user.dir is your programs current executing context...so it actually makes no sense to include it, you could just use midl.bat by itself (assuming the command exists within the current execution context)
I wrote a really simple batch file...
#echo off
dir
Which I put in my "C:\Program Files" directory, as I need a path with spaces and used....
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RunBatch {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder(
"cmd", "/c", "listme.bat"
);
pb.directory(new File("C:/Program Files"));
pb.redirectError();
try {
Process process = pb.start();
InputStreamConsumer.consume(process.getInputStream());
System.out.println("Exited with " + process.waitFor());
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
}
public static class InputStreamConsumer implements Runnable {
private InputStream is;
public InputStreamConsumer(InputStream is) {
this.is = is;
}
public static void consume(InputStream inputStream) {
new Thread(new InputStreamConsumer(inputStream)).start();
}
#Override
public void run() {
int in = -1;
try {
while ((in = is.read()) != -1) {
System.out.print((char) in);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}
To run it without any issues...
I am trying to compile a java class file in another java class file by using javac command. It went well if these two file do not have any package name with them.
Class Laj
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Laj {
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
if(pro.exitValue() != 0){
System.out.println(command + " exitValue() " + pro.exitValue());
}
}
public static void main(String[] args) {
try {
runProcess("javac simpleTest.java");
runProcess("java simpleTest");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Class SimpleTest
public class simpleTest {
public static void main(String[] args) {
System.out.println("What's wrong with it");
}
}
I can use the commands javac Laj.java and java Laj to compile and run them well. However if I add the package name, for example package compileTest in the front of these two classes and modify the runProcess part of the code in Laj to
runProcess("javac -d . compileTest.simpleTest.java");
runProcess("java compileTest.simpleTest");
the code would not work.
Can anyone help me, thank you.
Why do not you use 'JavaCompiler' class to compile your java file. Please see below example I have compiled a java class with package name.
Package Name = com.main
Class Name = MainClass.java
Source Dir = src
public void compileClass() {
System.setProperty("java.home", "G:\\Java\\Tools\\installed\\JDK"); // Set JDK path it will help to get compiler
File root = new File("/src"); // Source Directory
File sourceFile = new File(root, "com/main/MainClass.java"); // Java file name with package
sourceFile.getParentFile().mkdirs();
try {
new FileWriter(sourceFile).close(); // Read Java file
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
System.out.println(compiler.run(null, null, null, sourceFile.getPath()));
}
I was trying to use a restartApplication method that I found on stack overflow, but for some reason it only will restart my application once. For example, in this simple JOptionPane program below, if the user enters the letter "a", it will restart the program. Once the program restarts, if the user types in "a" again, it just terminates the execution. How can I enable it to restart itself continuously?
I added in some println() statements to see if I could get any more info, and it just confirmed that the program is ending right after I type in the letter "a" on the second time around.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class JOptionTest{
public static void restartApplication()
{
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File("C:\\Documents and Settings\\My Documents\\hello3.jar");//UpdateReportElements.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
public static void main(String[] args){
String str = JOptionPane.showInputDialog(null, "Enter some text",1);
System.out.println(str);
//String a= "a";
if (str.equals("a")){
System.out.println(str+ "right about to restart");
restartApplication();
}
}
}
See this line?
System.exit(0);
you are calling restartApplication a Single time and when it ends you exit the java process.
If you want to restart continuously, then remove this line and probably iterate forever:
public static void restartApplication()
{
while(true){
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
final File currentJar = new File("C:\\Documents and Settings\\XBBKKYL\\My Documents\\hello3.jar");//UpdateReportElements.class.getProtectionDomain().getCodeSource().get Location().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have not tested this, it's just an idea