Can't call Java program with arguments through PHP - java

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.

Related

How to run Java Eclipse from Excel VBA?

I have written the following code in Java:
public class test {
public static void main(String[] args) throws IOException {
FileWriter f = new FileWriter(new File("C:\\Users\\john\\Desktop\\x.txt"));
f.write("hello world!");
f.close();
}
}
It works correctly (creates a file called x.txt on the desktop containing "hello world!")
And I have this VBA script
Sub Macro1()
'
' Macro1 Macro
'
'
Dim objShell As Object
Dim JavaExe, JavaScript As String
Set objShell = VBA.CreateObject("Wscript.Shell")
JavaExe = """C:\Users\john\eclipse-workspace\eclipseCode\src\test.java"""
JavaScript = "C:\Users\john\Desktop\x.txt"
objShell.Run JavaExe & JavaScript
End Sub
But it does not execute the java code. It simply opens the file from java eclipse as a .txt file.
Is it possible to run java eclipse from Excel VBA? Any help is greatly appreciated, thanks.
What you want to implement in your "objShell.Run" is actually RUNNING Java from the command line with your program as an argument.
What you are ACTUALLY doing is pointing to the Java file and saying "Do this file" and the system is saying "OK. I know what to do with this. I open .java files in a text editor!".
Research how to compile & run java programs using javac/java.
To test this process, first ignore Eclipse and VBA and just go to a normal command prompt (cmd) and figure out the co mmands to compile & run the java to see what command line you need.
Hint: You will need to compile with javac & then run with java. Something like "javac test.java" and "java test" in the directory your file is in.
Should be straightforward from there.

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

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.

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

How can I read the arguments from a text file while running java

I have the below code
public class prob01 {
public static void main (String arg[]) {
System.out.println(arg[0]);
}
}
I have a text file prob01.txt in the same directory which contains: StackOverflow StackExchange
How can I get the output as StackOverflow from the above code when I give the arguments as prob01.txt like below: (I dont want to modify the java code, the dos has to take care of parsing the file and sending the contents as arguments)
C:\> javac prob01.java
C:\> java -cp . prob01 < prob01.txt
You'll need to use Reader in java code to read the content of the file.

Categories