Trying to compile and run c++ code with java code - java

I was trying to compile and run a c++ program from a java program, I made a .bat file having compilation and execution command, The code for making .bat file works fine, but code to open the .bat file doesn't work. It says "g++ is not recognized as an internal/external command", but if I open .bat file manually, it works fine. please help me with the code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Batch
{
FileOutputStream fos;
DataOutputStream dos;
public Batch()
{
}
public void createBat() throws Exception
{
File file=new File("M:\\AV\\compile_Execute.bat");
fos=new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeBytes("#echo off");
dos.writeBytes("\n");
dos.writeBytes("g++ main.cpp -o main.exe -lmingw32 -lSDL2main -lSDL2 & main.exe");
fos.close();
}
public void executeBat() throws Exception
{
String[] command = {"cmd.exe", "/C", "Start", "M:\\AV\\compile_execute.bat"};
Process p = Runtime.getRuntime().exec(command);
}
}

What happens here is that you messed up with the path, because the file is located in another drive, you cannot just use the path or go back a folder using ".."
Firstly, go to the biggest directory
cd "C:\"
Then, change drive
M:
Note that to change directoy you must be in the drive biggest folder and that to change drives, you must use the format letter:
These two steps can be simplified to cd D:
Next:
cd "M:\\AV\\"
Finally:
compile_execute.bat
Merging it, I would use this instead of just a path: cd /D M:\\AV\\ compile_execute.bat
I suggest reading about MS-DOS.
Thanks for the comment related to not being able to change directory to a file.

Related

Calling bash script from Java

I have this MCVE for an Java class calling a bash script:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Test
{
static BufferedReader in;
public static void main(String[] args) throws Exception
{
String[] cmd = new String[]{"/bin/sh", "/usr/myapp/myscript.sh", "parameter1"};
Process pr = Runtime.getRuntime().exec(cmd);
in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
}
}
When I have the compiled .class file in the same directory as myscript.sh, it works just fine.
As soon as I move the .class file to another folder, it doesn't execute the script anymore, although I am still using the absolute path to the script.
I tested this with JDK 1.8 on a BeagleboneBlack running Angstrom if this information is good for something.
How can I run the script, although it is in a different location?
Using the getErrorStream hint by Samuel really helped.
It was clear, that some sub-scripts that were in the same folder as the original shell script were not found.
The solution was as easy as using absolute paths to sub-scripts as well since the working directory is not the one of the called script but the one of the calling application (in my case the Java App)

execute java from php from different directory

I have linux server(Debian). I have java program(compiled) in directory (reza). I am trying to execute this java program from /var/www and through php script.
$com=shell_exec('java /reza/z');
When call in above format it dosent return any results or execute java program.
When I call one php script in reza folder with same call format it returns correct response:
$com=shell_exec('php /reza/a.php');
Any idea how to make this to work correctlly?
P.S. when call java from same directory from php it returns correct response:
$com=shell_exec('java z');
Java file is compiled and include class file too.
Java sample code is:
import java.io.*;
public class z{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}
Regards,
Finally solved this. Must change permission of target folder and enable "Write" too. Thanks all for helping me.
Use the classpath switch:
$com=shell_exec('java -cp /reza z');
Put the full path to Java executible in command (/usr/bin/java for example) . You may also need to set up class path etc with arguments. Remember that Java is executing in the context of the web server user, not your personal login, so the environment may not have the same variables defined with same values, such as JRE_HOME, PATH etc.
To find out what you have shell exec the env command to list the available environment variables, with php. I think phpinfo() will give you the same info.

Error: Could not find or load main class - path is correct

As you can see in the title, I'm getting the error:
Error: Could not find or load main class Exercise14_11.java
I checked my path and it should be working, when I type java -version in CMD I get the proper output. Which should indicate the system path is set correctly.
I'm opening the CMD from the same folder as where the Exercise14_11.java is located.
But when I typt: java Exercise14_11.java
I get the error:
Error: Could not find or load main class Exercise14_11.java
I've read the answers that has been asked for this error before but it has not really helped.
Hope someone can tell me whats wrong.
PS Here's the program I'm trying to run:
package hsleiden.webcat.exercise14_11;
import java.io.*;
import java.util.*;
public class Exercise14_11 {
public static void main(String[] args) throws Exception {
if (args.length != 2){
System.out.println("Usage: java Exercise14_11 stringTeVerwijderen sourceFile");
}
File sourceFile = new File(args[1]);
if(!sourceFile.exists()){
System.out.println("Source file " + args[1] + " does not exist");
}
Scanner input = new Scanner(sourceFile);
StringBuilder sb = new StringBuilder();
while(input.hasNext()){
String watVervangen = input.nextLine();
String vervangen = watVervangen.replaceAll(args[0], "");
sb.append("\r\n" + vervangen);
}
input.close();
PrintWriter output = new PrintWriter(sourceFile);
output.println(sb.toString());
output.close();
}
}
The origin of the problem seems to be that your class belongs to package hsleiden.webcat.exercise14_11, and you are working as it belonged to the default package. If you sucessfully compiled it, the .class file should be inside a directory C:\...\DDD\hsleiden\webcat\exercise14_11, and be named Exercise14_11.class. To run it, either
Add directory C:\...\DDD to the classpath, or
Add directory . to the classpath and cd to C:\...\DDD.
Additionally, the java command requires the full class name, so you should use:
java hsleiden.webcat.exercise14_11.Exercise14_11
Please note that when compiling it's correct to use the .java filename extension, but when running it's necessary to use a class name. These don't have a filename extension, so don't add .java or .class.
For example, if the .class file full path were C:\eclipse\IOPR2\Exercise14_11\bin\hsleiden\webcat\exercise14_11\Exercise14_11.class, then you would need to run it with:
java -cp C:\eclipse\IOPR2\Exercise14_11\bin hsleiden.webcat.exercise14_11.Exercise14_11
You have to compile the class, and then run it. You have wrong command:
javac Exercise14_11.java
java Exercise14_11
javac command takes the source files and produces the compiled classes
java command takes the compiled class with main method to execute

Can't call Java program with arguments through PHP

I'm trying to connect a Java project with a website. The project is located in "website_folder/data/backend" and at that time, I want to test if the following example works:
[java code]
public static void main(string args[]) {
if(args[0].equals("5") {
File f = new File("/location/to/file/result.txt");
if(!f.exists()) {
f.createNewFile();
FileWriter fstream = new FileWriter("/location/to/file/result.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("It works!");
out.close();
}
}
}
And in the PHP file I have to following command:
<?php
exec("java -cp /data/backend/Project/build/classes/project/Main.class/ main 5",$output);
?>
but nothing happens! I mean, the file isn't created in the directory I have specified in the main method. I have tried to run the .jar file of the project in the PHP command, to pass the argument "5" via a variable, to add to the directory path -in the exec command- this: "i:/xampp/htdocs/website_folder/" (I:\ is the disk drive where I have my virtual server -xampp- installed), but in vain. Am I doing something wrong with the syntax of the command?
Edit:
I changed the command to point the .jar file (java -jar /data/backend/Project/dist/Project.jar 5) and the problem is solved.
Try this:
"java -cp /data/backend/Project/build/classes/ project.Main 5"
This assumes, that the class which contains your main method is in package project and is called Main. If this is not the case, adapt accordingly.

Creating and using .exe in JAR

I have some code written in Java that executes some .exe file. It first creates a temporary file from where it executes it and then destroys that file after the execution is done.
The only problem with this is, it requires the executable file to be in the same package as that of the class having main function. I want to place and access my .exe file from other locations as well because while creating the JAR file of my project it never executes that exe file.
Is there some other way by which my .exe file can also be a part of my JAR file irrespective of its location in my project?
Here's the code :
package com.web.frame;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
//import java.net.URL;
public class Test{
public void Test1(String fileAddr,String filename, String destFilenam) throws Exception {
// Place .exe into the package folder.
InputStream src =this.getClass().getResourceAsStream("DECRYPT.exe");
if(src!=null) {
File exeTempFile = File.createTempFile("dspdf", ".exe");
byte []ba=new byte[src.available()];
src.read(ba,0,ba.length);
exeTempFile.deleteOnExit();
FileOutputStream os=new FileOutputStream(exeTempFile);
os.write(ba,0,ba.length);
os.close();
String hello=exeTempFile.getParent();
System.out.println("Current Directory Of file : "+hello);
String hello1=exeTempFile.getName();
System.out.println("Full Name Of File : "+hello1);
int l=hello1.length();
l=l-4;
char[] carray=hello1.toCharArray();
String s = new String(carray,0,l);
System.out.println(s);
String param="cmd /c cd "+hello+" && "+s+" d 23 11 23 "+fileAddr+"\\"+filename+" "+destFilenam;
Runtime.getRuntime().exec(param);
Runtime.getRuntime().exec("c:\\Program Files\\VideoLAN\\VLC\\vlc.exe "+hello+"\\"+destFilenam);
Runtime.getRuntime().exec("cmd /c del"+hello+"\\"+destFilenam);
}
else
System.out.println("Executable not found");
}
}
The maximum you can do is place your exe anywhere in your classpath. Ensure that the jar's manifest has a classpath element. Then you should be able to access the exe by saying Test.class.getResourceAsStream("")
So create a folder, put the exe into that folder and include the folder in your classpath.

Categories