How can I close a Java application from another Java application? - java

I am using the following code for running an application:
private void RunApp2() throws IOException
{
StringBuilder sb = new StringBuilder();
String filePath = System.getProperty("user.dir");
String jarfile = filePath + "\\MyAppV2.jar";
File f = new File(jarfile);
if(f.exists() && !f.isDirectory()) {
// do something
}
else
{
AreThereProblem = true;
}
try { // jarname arguments has to be saperated by spaces
Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar \""+jarfile + "\"");
//.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line).append("\n");
}
System.out.println("Console OUTPUT : \n"+sb.toString());
//process.destroy();
}catch (Exception e){
lblInformation.setText(e.getMessage());
}
}
But how can I close MyAppV2.jar application if it is already running before I'm running it again?

Related

csc -version is running in terminal but not from my java program MAC

package test_cmd_command;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
public class CommandLine {
public static String executeCommand(String cliCommand) {
String s = null;
BufferedReader stdInput = null;
BufferedReader stdError = null;
String error = "";
String output = "";
try {
ProcessBuilder pb1 = new ProcessBuilder(
"bash",
"-c",
cliCommand);
pb1.redirectErrorStream(true);
Process p = pb1.start();
stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
output += "\n" + s;
}
//System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
//System.out.println(">> "+s.toString());
error += "\n" + s;
}
} catch (IOException e) {
System.out.println("exception happened - here's what I know: \n" + e.getMessage());
} finally {
try {
stdInput.close();
stdError.close();
} catch (IOException e) {
}
}
String returnValue = null;
if (output != null && error != null) {
returnValue = output + "\n" + ": " + error;
} else if (output != null) {
returnValue = output;
}
return returnValue;
}
}
"csc -version" is running in terminal but not from my java program on MAC.
it give Output "bash Command Not Found".
Is any way to solve this issue....
This program run other commands correctly like javac -version etc.
I am running this program on MAC not on windows.
This work for me
export PATH=/Library/Frameworks/Mono.framework/Versions/Versions/bin/:${PATH}
I run command like this "export PATH=/Library/Frameworks/Mono.framework/Versions/Versions/bin/:${PATH}; csc -version" and it works and return version of csc.

Java - How to call python classes using processbuilder

How do I call and execute python class methods from java. My current java code works, but only if I write:
if __name__ == '__main__':
print("hello")
But I want to execute a class method, regardless of if __name__ == '__main__':
Example python class method I would like to run:
class SECFileScraper:
def __init__(self):
self.counter = 5
def tester_func(self):
return "hello, this test works"
Essentially I would want to run SECFileScraper.tester_func() in java.
My Java code:
try {
ProcessBuilder pb = new ProcessBuilder(Arrays.asList(
"python", pdfFileScraper));
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
int exitCode = p.waitFor();
System.out.println("Exit Code : " + exitCode);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null) {
System.out.println("Python Output: " + line);
}
} catch (Exception e) {
e.printStackTrace();
}
pdfFileScraper is the file path to my python script.
I've tried jython, but my python files use pandas and sqlite3, which can't be implemented using jython.
So if I understand your requirement, you want to invoke a class method in pdfFileScraper.py. The basics of doing this from the shell would be something akin to:
scraper=path/to/pdfFileScraper.py
dir_of_scraper=$(dirname $scraper)
export PYTHONPATH=$dir_of_scraper
python -c 'import pdfFileScraper; pdfFileScraper.ClassInScraper()'
What we do is get the directory of pdfFileScraper, and add it to the PYTHONPATH, then we run python with a command that imports the pdfFileScraper file as a module, which exposes all the methods and classes in the class in the namespace pdfFileScraper, and then construct a class ClassInScraper().
In java, something like:
import java.io.*;
import java.util.*;
public class RunFile {
public static void main(String args[]) throws Exception {
File f = new File(args[0]); // .py file (e.g. bob/script.py)
String dir = f.getParent(); // dir of .py file
String file = f.getName(); // name of .py file (script.py)
String module = file.substring(0, file.lastIndexOf('.'));
String command = "import " + module + "; " + module + "." + args[1];
List<String> items = Arrays.asList("python", "-c", command);
ProcessBuilder pb = new ProcessBuilder(items);
Map<String, String> env = pb.environment();
env.put("PYTHONPATH", dir);
pb.redirectErrorStream();
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
int exitCode = p.waitFor();
System.out.println("Exit Code : " + exitCode);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null) {
System.out.println("Python Output: " + line);
}
}
}
You can also call Python lib directly via JNI. This way, you don't start new process, you can share context between script calls, etc.
Take a look here for a sample:
https://github.com/mkopsnc/keplerhacks/tree/master/python
This is my java class that worked for me.
class PythonFileReader {
private String path;
private String fileName;
private String methodName;
PythonFileReader(String path, String fileName, String methodName) throws Exception {
this.path = path;
this.fileName = fileName;
this.methodName = methodName;
reader();
}
private void reader() throws Exception {
StringBuilder input_result = new StringBuilder();
StringBuilder output_result = new StringBuilder();
StringBuilder error_result = new StringBuilder();
String line;
String module = fileName.substring(0, fileName.lastIndexOf('.'));
String command = "import " + module + "; " + module + "." + module + "." + methodName;
List<String> items = Arrays.asList("python", "-c", command);
ProcessBuilder pb = new ProcessBuilder(items);
pb.directory(new File(path));
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = in.readLine()) != null)
input_result.append("\n").append(line);
if (input_result.length() > 0)
System.out.println(fileName + " : " + input_result);
while ((line = out.readLine()) != null)
output_result.append(" ").append(line);
if (output_result.length() > 0)
System.out.println("Output : " + output_result);
while ((line = error.readLine()) != null)
error_result.append(" ").append(line);
if (error_result.length() > 0)
System.out.println("Error : " + error_result);
}}
and this is the way that you can use this class
public static void main(String[] args) throws Exception {
String path = "python/path/file";
String pyFileName = "python_name.py";
String methodeName = "test('stringInput' , 20)";
new PythonFileReader(path, pyFileName, methodeName );
}
and this is my python class
class test:
def test(name, count):
print(name + " - " + str([x for x in range(count)]))

Process No Wait for Terminate a Bat File

I create a .bat file in my java application(Runtime),then run .bat file and use of waitFor() method to waiting for terminate .bat file,but process no wait for terminate .bat file.
Code:
public boolean restoreDepot() {
try {
InputStreamReader _input = new
InputStreamReader(getClass().getResourceAsStream("/Depot/DBMakaseb.sql"));
BufferedReader _in = new BufferedReader(_input);
String _currentpath = (new File(".")).getCanonicalPath() + File.separator + "DBDepot.sql";
BufferedWriter _out = new BufferedWriter(new FileWriter(_currentpath));
while (_in.ready()) {
_out.write(_in.readLine());
_out.newLine();
}
_in.close();
_out.close();
String _comCur = "set cur=%cd%";
String _comCD = "Cd /d %PROGRAMFILES%\\MySQL\\MySQL Server 5.5\\bin";
String _comando = "mysql -u root -pm117988m < %cur%" + "\\DBDepot.sql";
String _comExit = "exit";
BufferedWriter _out1 = new BufferedWriter(new FileWriter("restore.bat"));
_out1.write(_comCur);
_out1.newLine();
_out1.write(_comCD);
_out1.newLine();
_out1.write(_comando);
_out1.newLine();
_out1.write(_comExit);
_out1.close();
Process _p = Runtime.getRuntime().exec("cmd /C start restore.bat");
int _res = _p.waitFor();
while (!(((new File(_currentpath)).delete()) && ((new File((new File(".")).getCanonicalPath() + File.separator + "restore.bat")).delete()))) {
}
if (_res != 0) {
return false;
}
return true;
} catch (Exception err) {
System.out.println(err);
}
return false;
}
Please Help me!
It has to do with your usage of start.
Remove start, only to leave
Process _p = Runtime.getRuntime().exec("cmd /C restore.bat");

How to compile & run java and C file from java code?

I am working on an Editor application where I can compile and run c,cpp and Java file.I am developing this application using java programming language.I am developing it in Eclipse.
I am able to create new files(c,cpp and java) on specific locations and also I am able to save file to different-2 locations.
And for execution I am using following methods.
String compileFileCommand = "javac "+fileName;
Process compile_process = new ProcessBuilder(compileFileCommand).redirectErrorStream(true).start();
compile_process.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(compile_process.getInputStream()));
String line=reader.readLine();
while(line!=null) {
System.out.println(line);
line=reader.readLine();
}
My problem is that I am not able to compile files from their corresponding locations.
Always giving Exception
java.io.IOException: error=2, No such file or directory
Please tell me how can I compile and run all c,c++ & java files.
Please also give me any other suggestion for my application.
Edited ..
I have used these two methods for compiling and running.On Compiling it creates a class file in case of Java.But all the time I am getting null from InputStreams(both getErrorStream() and getInputStream()).
void compileJavaFile(String fileName)
{
String compileFileCommand = "javac " + fileName;
try
{
System.out.println("Executing Java File");
Process compileProcess = Runtime.getRuntime().exec(compileFileCommand);
String line = "";
BufferedReader bri = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
while ((line = bri.readLine()) != null)
{
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null)
{
System.out.println(line);
}
bre.close();
compileProcess.waitFor();
System.out.println("Done.");
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runJavaFile(String fileName)
{
String runFileCommand = "java " + fileName.split(".java")[0];
try
{
System.out.println("runFileCommand : " + runFileCommand);
System.out.println("Running Java File");
Process runProcess = Runtime.getRuntime().exec(runFileCommand);
BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String line = reader.readLine();
System.out.println("line = " + line);
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
And for C and C++ I am using.
void compileCFile(String fileName)
{
String compileFileCommand = "gcc " + fileName;
resultString = "";
try
{
System.out.println("Compiling C File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".c")[0];
try
{
System.out.println("Running C File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void compileCPPFile(String fileName)
{
String compileFileCommand = "g++ " + fileName;
try
{
System.out.println("Compiling CPP File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCPPFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".cpp")[0];
try
{
System.out.println("Running CPP File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
In case of C and C++ it show error like
g++: /media/disk/eclipse/\/UniversalIDE/CPP/firstCPP: No such file or directory
Please give me solution for my problems ..
Please try following,
Process p = Runtime.getRuntime().exec(command);
command is a string you pass. in command you can pass "javac Test.java" to compile your java file & just like that you can use other commands.
replace the line
String runFileCommand = "./" + fileName.split(".c")[0];
with
String runFileCommand = "./a.out";

Fetch and store output from a subprocess in Java

I'm working on something that requires me to start to subprocess(command prompt) and execute some commands on it. I need to fetch the output from the subprocess and store it in a file or String.
here's what I have done so far, and it doesn't work:
public static void main(String args[])
{
try
{
Runtime RT = Runtime.getRuntime();
String command = "cmd /c start javap java.lang.String";
File file = new File("write.txt");
Writer output = new BufferedWriter(new FileWriter(file));
BufferedReader br = new(BufferedReader(newInputStreamReader(RT.exec(command).getInputStream()));
String temp = br.readLine();
while(!temp.equals(null))
{
output.write(temp);
temp = br.readLine();
}
output.close();
RT.exec("exit");
}
catch(Exception e)
{
System.out.println(e);
}
}
Start changing this:
new(BufferedReader(newInputStreamReader(
To:
new BufferedReader(new InputStreamReader(
Compile and see if you still have the problem
edit
Also, there is a good reason why you shouldn't catch Exception, you also catch programming errors like a NullPointerException
while( !temp.equals(null)) { //Throws NullPointerExceptin when temp is null
Change it with:
while( temp != null ) { //!temp.equals(null)) {
Finally you don't have to "exit" since you're not inside the cmd really.
Corrected version
This version runs as you intend:
import java.io.*;
class Rt {
public static void main(String args[]) throws Exception {
Runtime RT = Runtime.getRuntime();
String command = "javap java.lang.String" ;
File file = new File("write.txt");
Writer output = new BufferedWriter(new FileWriter(file));
BufferedReader br = new BufferedReader(new InputStreamReader(RT.exec(command).getInputStream()));
String temp = br.readLine();
while( temp != null ) { //!temp.equals(null)) {
output.write(temp);
temp = br.readLine();
}
output.close();
//RT.exec("exit");
}
}
edit
Final remarks:
Since Java 1.5 the preferred way to invoke a command is using ProcessBuilder and it is better if you use an array of strings instead of a single string ( or varargs ).
When you're building your output you can get rid of the file object and pass the file name directly to the filewriter.
While reading the line you can assign and evaluate in the condition.
Java's coding conventions suggest to use the opening brace in the same like.
This would be my version of your code:
class Rt {
public static void main(String args[]) throws Exception {
Writer output = new BufferedWriter(new FileWriter ( "write.txt"));
InputStream in = new ProcessBuilder("javap", "java.lang.String").start().getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(in));
String line = null;
while( ( line = br.readLine() ) != null ) {
output.write( line );
}
output.close();
}
}
It might need still some work, but I hope it helps you.
Here is an example which should work:
StringBuffer outStream = new StringBuffer();
StringBuffer errStream = new StringBuffer();
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec(command);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
InputStream outIs = process.getInputStream();
MonitorOutputThread sout = new MonitorOutputThread(outIs, outStream);
sout.run();
InputStream errIs = process.getErrorStream();
MonitorOutputThread serr = new MonitorOutputThread(errIs, errStream);
serr.run();
while (sout.isAlive() || serr.isAlive()) {
try {
sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
// ignore
}
}
And the code for MonitorOutputThread
private class MonitorOutputThread extends Thread {
private final InputStream is;
private final StringBuffer output;
public MonitorOutputThread(InputStream is, StringBuffer output) {
this.is = is;
this.output = output;
}
#Override
public void run() {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
try {
while ((line = br.readLine()) != null) {
output.append(line);
output.append(LINE_SEPARATOR);
}
if (output.length() >= 1) {
char lastChar = output.charAt(output.length() - 1);
if (lastChar == '\n') {
output.deleteCharAt(output.length() - 1);
}
}
} catch (IOException ex) {
ex.printStackTrace();
return;
}
}
}
This should catch both the standard output and standard error of the command.
DevDaily has a simple example of how to work with Process class.
See the snippet:
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// run the Unix "ps -ef" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("ps -ef");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
or even check this code I've writen some time ago

Categories

Resources