Running 2 cmd codes at runtime in java - java

I want to run 2 cmd commands consecutively. My purpose here, first compile file(with using cmd command not any other things like Java Compiler API), then run.
compiler.java:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class compiler {
public static void main(String[] args) {
final String dosCommand = "cmd /c java -cp ";
final String classname = "example";
final String location = "D:\\";
try {
final Process process2 = Runtime.getRuntime().exec("cmd /k javac D:\\example.java"); //I used /k to remain.
final Process process = Runtime.getRuntime().exec(dosCommand + location + " " + classname);
final InputStream in = process.getInputStream();
final InputStream in2 = process.getErrorStream();
int ch, ch2;
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
while ((ch2 = in2.read()) != -1) {
System.out.print((char) ch2); // read error here
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
example.java:(in D:// path.)
public class example {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
When I run compiler.java it gives
Error: Couldn't find or load main class example
No problem in example.java. When I compile and run this example.java file in cmd it runs correctly.
My problem is to run 2 cmd commands consecutively. Finally, How can I run cmd commands consecutively?. Thanks...

Related

postgresql command not executing successfully through java code

I have installed the postgresql database and I have to fire few commands on this database through my java code. But the commands are not executing through java code. If I fire the same commands through command prompt they gets execute. Below is my java code:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MyMultipleCommandsEx {
public static void main(String a[]) throws InterruptedException{
List<String> commands = new ArrayList<String>();
commands.add("CMD");
commands.add("/c");
commands.add("SET PGPASSWOR=test_admin");
commands.add(psql.exe --dbname=postgres --username=test_admin --port=5433 --command="\"CREATE schema test;\"");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("C:\\Program Files\\PostgreSQL\\9.5\\bin"));
try {
Process prs = pb.start();
int e = prs.waitFor();
System.out.println("Echo command executed, any errors? " + (e == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(prs.getInputStream()));
System.out.println("Error code:"+e);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

Read a .java file from another class and call its method

Is it possible that to read a .java file as a file (using file path)from another class and call its method in this class ?
Lets takes a java class as
public Mylogic {
public static void test()
{
 //some logic
}
}
Is there a way another java class can read Mylogic.java file as a file and execute test() method
?
Why I want this?
Once source code goes into application server , then if I have to add another class , I have to wait for complete deployment which takes time.If I am able to do this, I can keep a utility class ready in source code to read .java file from dir and execute it without any deployment, thus saving time.
This is for higher environment (production mode) so no exploded mode.
It is possible, if you have JDK instead of JRE when running the code, using javax.tools.JavaCompiler and a customized class loader:
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class LoadAndRun extends ClassLoader {
public Class findClass(String name) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
InputStream in = new FileInputStream("./" + name + ".class");
byte [] buff = new byte[4096];
while (true) {
int c = in.read(buff);
if (c == -1) break;
out.write(buff, 0, c);
}
return defineClass(name, out.toByteArray(), 0, out.toByteArray().length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
// Try to get the system compiler
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
System.err.println("System java compiler not found.");
return;
}
// Prepare the java file to be compiled
String classname = "LoadAndRun" + System.currentTimeMillis();
File javaFile = new File(classname + ".java");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(javaFile)));
writer.write("public class " + classname + "{\n");
writer.write("public static void test() {System.out.println(\"this is the test class:\"+"+classname+".class);}");
writer.write("}\n");
writer.close();
// Compile it!
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjects(javaFile)).call();
// Load and invoke static method
ClassLoader classLoader = new LoadAndRun();
Class cls = classLoader.loadClass(classname);
Method m = cls.getMethod("test");
m.invoke(null);
// Clean up
m = null;
cls = null;
classLoader = null;
System.gc();
javaFile.delete();
File classFile = new File(classname + ".class");
classFile.delete();
}
}

Can you run a java class from within a java program?

I have been creating a program that writes and run java classes. So far I have been able to write a "Runable.java" class but not able to run it. I have tried to run a "runjava.bat" and get the .bat to run the "Runable.java" class but I keep getting a "Error: Could not find or load main class application.Runable.class". I was wondering what I am doing wrong or if there is a better way to go about running a java class from within a java program?
Here is my code(Simplify Slightly):
Main.java:
package application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.stage.FileChooser;
public class Main {
final static String Program =
"package application;\n"
+ "public class Runable {\n"
+ "public static void main(String[] args) {\n"
+ "System.out.println(\"Hello\");\n"
+ "}\n"
+ "}\n";
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
while(true){
System.out.println("State a comand.");
String Command = s.nextLine();
if (Command.equalsIgnoreCase("Write") || Command.equalsIgnoreCase("Save")){
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = new File("src/application/Runable.class");
if(file != null){
SaveFile(Program, file);
}
}
else if (Command.equalsIgnoreCase("Run") || Command.equalsIgnoreCase("Play")){
ProcessBuilder builder = new ProcessBuilder(
"src/runjava.bat");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
else if (Command.equalsIgnoreCase("End") || Command.equalsIgnoreCase("Exit")){
Platform.exit();
}
else{
System.err.println("Command not recognized.");
System.err.println("Please try again.");
}
}
}
private static void SaveFile(String content, File file){
try {
FileWriter fileWriter = null;
fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
runjava.bat:
javac "src\application\Runable.java"
java application.Runable.class
and Runable.java if you didn't get it from the Main.java:
package application;
public class Runable {
public static void main(String[] args) {
System.out.println("Hello");
}
}
The java command expects a class name, not a filename. Unless your class is called "class" in the package "application.Runable" (which it isn't) you probably wanted to use:
java application.Runable
Because you can't execute a .java file like that. You must first compile it to get a .class file, and change the code that executes the class to point to Runable.class
The reason it is not running, is because the .java file is the code you type, and the .class file is the compiled version of the code that Java Virtual Machine executes.
Another solution to compile and run the program compared to executing the .bat file is to use the javax.tools API or another library based off of it. I have found InMemoryJavaCompiler library that makes it easy to compile and run the programs. This approach means that the program will run on the same JVM as your UI which may be helpful.
The following code shows how you might invoke the program using the library.
try{
Class<?> clazz = InMemoryJavaCompiler.compile("apllication.Runable", Program);
clazz.getMethod("main", String[].class).invoke(null, new String[0]);
}catch(Exception e){
e.printStackTrace();
}
In your Main.java's "Run" block, you should have
ProcessBuilder builder = new ProcessBuilder("runjava.bat");
In your runjava.bat, you should have (as immibis said)
javac -d . src/application/Runable.java
java application.Runable
** not Runable.class in the second line.
And runjava.bat should be placed in parallel with the parent folder of application\ but not the src\application folder. In other words, you should have something like classes\runjava.bat, classes\application\Main.class and classes\application\Runable.class. Hope it helps.

Executing Ubuntu commands from java program

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MyCommand {
public static void main(String[] args) {
String [] commandList = {"/bin/bash","-c", "/home/atul/Desktop/javaprogramm/" , "mkdir newmanisha" , "mkdir newmanisha"};
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(commandList);
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Trying to execute this but nothing happens . I am using ubuntu 13.10.how to do cd in ubuntu using java program. I have used "-c" but it is not working.
Just replace the commandList related line with the following line. That should work ..
String [] commandList = {"/bin/bash", "-c", "cd /home/atul/Desktop/javaprogramm/ && mkdir newmanisha && mkdir newmanisha"};

ProcessBuilder cannot run bat file with spaces in path

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...

Categories