Am trying to run the source code from this link
Compile and run source code from Java application
I installed the Mingw32 compiler changed the compiler location path and getting this error when running a sample .cpp file in Eclipse.
public class C_Compile {
public static void main(String args[]){
String ret = compile();
System.out.println(ret);
}
public static String compile()
{
String log="";
try {
String s= null;
//change this string to your compilers location
Process p = Runtime.getRuntime().exec("cmd /C \"C:\\MinGW\\bin\\mingw32-gcc-4.6.2.exe\" C:\\MinGW\\bin\\Hello.cpp ");
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
boolean error=false;
log+="\n....\n";
while ((s = stdError.readLine()) != null) {
log+=s;
error=true;
log+="\n";
}
if(error==false) log+="Compilation successful !!!";
} catch (IOException e) {
e.printStackTrace();
}
return log;
}
public int runProgram()
{
int ret = -1;
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /c start a.exe");
proc.waitFor();
ret = proc.exitValue();
} catch (Throwable t)
{
t.printStackTrace();
return ret;
}
return ret;
}}
Errors:
mingw32-gcc-4.6.2.exe: error: CreateProcess: No such file or directory
Can anyone tell me where to place my Source .cpp File. Thanks
The error message indicates, that the gcc compiler itself was not found.
Why don't you use gcc.exe instead of mingw32-gcc-4.6.2.exe anyway? If you do an update of MinGW, the latter will get invalid!
Also you do not need to use \" in the string, when the path does not contain whitespace characters.
You can place your cpp file then anywhere you want, providing the path to that gcc. Exec should also have a parameter dir, that you can set to the directory of your cpp.
public static void CompileCprog(String filename){
File dir = new File("C://Users//JohnDoe//workspace//Project");
try {
String exeName = filename.substring(0, filename.length() - 2);
Process p = Runtime.getRuntime().exec("cmd /C gcc " + filename + " -o " + exeName, null, dir);
// Process p = Runtime.getRuntime().exec("cmd /C dir", null, 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 works perfectly for me.
The "dir" variable can be set to any location you want.
The first "p" process compiles a program and produces a .exe file with the same name (minus the .c) in the same location of the program you are compiling.
The buffered reader can be used if there is output from your command.
If you changed the command string to .exec("cmd /C dir"); the result of this will be printed in the output. (im using eclipse)
Related
I am trying to run a shell command from my application directory and I am getting "working directory null and environment null.
I have looked at several posts here but I'm not quite sure where to go from here.
Error:
Error running exec(). Command: [/data/user/0/com.netscout.iperf3_clientls] Working Directory: null Environment: null
public void startApp() {
StringBuffer output = new StringBuffer();
Process process = null;
String appFileDir = getApplicationInfo().dataDir;
// String commandLine = appFileDir + "/iperf3 -c 129.196.197.116 --forceflush -O3 -Z -P2";
String commandLine = appFileDir + "ls";
try {
process = Runtime.getRuntime().exec(commandLine, null, null);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
// output.append(line + "/n");
Log.e("Line", String.valueOf(line));
Log.e("output", String.valueOf(output));
}
} catch (IOException e) {
e.printStackTrace();
Log.i("Output", String.valueOf(e));
}
}
Try setting a working directory for the script to run from. Also I would suggest to use a ProcessBuilder for doing your job:
https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
I am trying to make my own Java IDE, however i am having problems getting the input from user after displaying the program itself
I have so far tried 2 ways of getting the console to appear.
Using Create Java console inside a GUI panel
or using my own code of
void runCommand(String command)
{
try {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", command);
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);
}
} catch (IOException ex) {
Logger.getLogger(FileToClass2.class.getName()).log(Level.SEVERE, null, ex);
}
}
void createClass(String dir, String filename)
{
//TODO: stop using exact java path / compile all .java in a dir
runCommand("cd "+dir+" && \"C:\\Program Files\\Java\\jdk1.8.0_91\\bin\\javac\" " + filename);
}
void runClass(String dir, String filename)
{
//TODO: allow use of packages etc
runCommand("cd " + dir + " && java " + filename);
}
This above code simply gets the output of the cmd terminal, the problem both these approaches have is the lack of input say if the user wanted to do a Scanner nextLine()
Is there any solution to this?
I have to execute two commands in terminal from my java program. Here is the java code that I am using :
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Runterminal {
public static void main(String[] args) {
Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 hello.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{
proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));
String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}
procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}
}
}
My hello.cpp file is stored in the home directory. When I compile the java program it gets compiled but while running it it is throwing exception. Here's the output which I am getting :
Exception occurred java.io.IOException: Cannot run program "aarch64-
linux-g++": error=2, No such file or directory
Try to replace using following lines in your code,
String compileCommand = "g++ -std=c++14 hello.cpp";
String runCommand = "./a.out";
And keep the .cpp file in same directory where the .class file lies.
I have made a cross compiler using gcc. Now I want the compile and run commands to be executed in a terminal through java program. Here is the code that I am using for this :
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Runterminal {
public static void main(String[] args) {
Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 test.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{
proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));
String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}
procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}
}
}
Now my first command is executing since I could see the a.out file being generated. The second command should dump the memory contents of file and it should print in in terminal but I am not seeing any output. Can anyone tell where I am going wrong?
I am searching files based on extension. Now for each file found, want to run a command:
Lets assume file found: C:\Home\1\1.txt. My exe exists in: C:\Home\Hello.exe
I would like to run command something like: "C:\Home\Hello.exe C:\Home\1\1.txt"
similarly for C:\Home\ABC\2.txt - "C:\Home\Hello.exe C:\Home\ABC\2.txt"
Kindly help me how to pass a searched file as an input to execute a command.
Thanks,
Kino
You can use below program as a base and then customize further as per your rqeuirement
public class ProcessBuildDemo {
public static void main(String [] args) throws IOException {
String[] command = {"CMD", "/C", "dir"}; //In place of "dir" you can append the list of file paths that you have
ProcessBuilder probuilder = new ProcessBuilder( command );
//You can set up your work directory
probuilder.directory(new File("c:\\xyzwsdemo")); //This is the folder from where the command will be executed.
Process process = probuilder.start();
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:\n",
Arrays.toString(command));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Wait to get exit value
try {
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Lets get you started:
Filter files using: FilenameFilter:
http://docs.oracle.com/javase/7/docs/api/java/io/FilenameFilter.html
Sample:
http://www.java-samples.com/showtutorial.php?tutorialid=384
And after you have got the files:
Use ProcessBuilder to execute:
http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
Sample:
http://www.xyzws.com/Javafaq/how-to-run-external-programs-by-using-java-processbuilder-class/189
If you are running your app from the command line (e.g. windows cmd), and your program name is Hello.java, only thing you have to do is to put in the argument, just like you did in your example. So it looks something like:
java Hello C:\Home\1\1.txt
I did not use exe, since this is an example, and the question is tagged with "java" tag.
Your Hello.java MUST have a main method that looks like this:
public static void main(String ... args) {
}
The parameter args are the actual parameters you enter in the command line. So to get the file name, you would have to do this:
public static void main(String ... args) {
String fileName= args[0];
}
And that's it. Later on, you can do with that whatever you want, i.e. open and edit a file:
File file= new File(fileName);
//do whatever with that file.
This code will help you
public static void main(String args[]) {
String filename;
try {
Runtime rt = Runtime.getRuntime();
filename = "";//read the file na,e
Process pr = rt.exec("C:\\Home\\Hello.exe " + filename );
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Error "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}