Running java program from another java program - java

I'm trying to run a Java program from another Java application. Here is my code:
public class Main {
public static int Exec() throws IOException {
Process p = Runtime.getRuntime().exec("javac -d C:/Users/Dinara/Desktop/D/bin "
+ "C:/Users/Dinara/Desktop/D/src/test.java");
Process p1 = Runtime.getRuntime().exec("java -classpath C:/Users/Dinara/Desktop/D/bin test");
return 0;
}
public static void main(String[] args) throws IOException {
Exec();
}
}
javac works fine and creates test.class file in bin directory. However java -classpath C:/Users/Dinara/Desktop/D/bin test does not run the test.class file.
the content of the test.java:
import java.io.*;
class test {
public static void main(String args[]) {
try {
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
I suppose that something wrong with recognizing Java command. Could you please give me a sample code for fixing this problem or share idea? I'm using Netbeans to run Main class and the location of the application folder is C:\Users\Dinara\Main

Use
System.getProperty("java.home") + "/bin/java -classpath C:/Users/Dinara/Desktop/D/bin test"
instead of
"java -classpath C:/Users/Dinara/Desktop/D/bin test"

You need to supply the full path to the javac, exec won't use the ath to find it for you

Related

Can't use java.io.* on CodeRunner

import java.io.*;
public class WriteFile {
public static void main(String[] args){
try {
FileWriter writer = new FileWriter("Test.txt");
writer.write("this is a plain text file.\n");
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
错误: 找不到或无法加载主类 O:WriteFile
原因: java.lang.ClassNotFoundException: O:WriteFile
This code can run on both eclipse and vs Code but not on Coderunner. How to solve it.
Your classpath is broken.
Method #1
Try adding the classpath while running it.
On windows:
java -classpath .;yourjar.jar YourMainFile
On Unix:
java -classpath .:yourjar.jar YourMainFile
Method#2
Configure the build path in your IDE and add an external JAR containing your class to the build path.
Method#3
Please read this to resolve the issue.
Note:
You could also refer to this.

Error running RMI application in Visual Studio Code [duplicate]

I'm programming a simple rmi application, and I have a problem.
If I run the registry in the same directory, it works; but if I change the directory from which I run the registry, it does not.
The registry would work generically from another host, but only the change of directory stop his functionality.
I'm working on this problem by 3 days without solution, I change also every possible configuration of the codebase parameter but nothing.
I describe the situation and code with the directory:
fileserver.java :
`package testrmi2;
import java.rmi.*;
public interface fileserver extends Remote {
public void scrivifile(String nomefile, String arg) throws RemoteException;
}
`
fileserverimpl.java:
package testrmi2;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileserverimpl extends UnicastRemoteObject implements fileserver{
public fileserverimpl() throws RemoteException {
super();
}
public void scrivifile(String nomefile, String arg) throws RemoteException {
try {
FileWriter myfile = new FileWriter(nomefile);
myfile.write(arg);
myfile.close(); }
catch (Exception e) {System.out.println(e);}
}
public static void main (String arg[]) {
try {
fileserverimpl s = new fileserverimpl();
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String codebase = System.getProperty("classpath");
System.out.println("Trying to access code base: " + codebase+"\n\nuse is "+System.getProperty("useCodebaseOnly"));
Naming.rebind("//127.0.0.1:2005/fileserverimpl", s);
System.out.println("Server attivato.");
} catch (Exception e) {System.out.println("errore inizializzazione server\n\n"+e.getMessage()+"\n\n\n");
}}}
client.java:
package testrmi2;
import java.rmi.*;
import java.io.*;
public class client {
public static void main (String arg[]) {
fileserver myserver;
String nomefile=" ";
String testo=" ";
System.out.println("Scrivi il nome del file");
nomefile=ReadString();
System.out.println("Scrivi il testo");
testo=ReadString();
try {
myserver = (fileserver) Naming.lookup("//127.0.0.1:2005/fileserverimpl");
myserver.scrivifile(nomefile, testo);
} catch (Exception e) {System.out.println(e);}
}
public static String ReadString() {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));
String s=" ";
try{
s=stdIn.readLine();
}
catch(IOException e) {System.out.println(e.getMessage()); }
return s;
}
}
and the policy file is:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
all this files are on the directory:
/Users/franco/Desktop/prova
to compiling it I goes in the /Users/franco/Desktop/prova directory and do in terminal :
javac -cp . -d . *.java
rmic rmic testrmi2.fileserverimpl
jar cvf testrmi2.jar testrmi2/fileserver.class testrmi2/fileserverimpl_Stub.class
after I run registry in another terminal with the following commands but in another directory:
export classpath=""
rmiregistry 2005 &
Finally I would to run the filesereveimpl.class goes with terminal in the /Users/franco/Desktop/prova directory and write :
java -classpath /Users/franco/Desktop/prova/ -Djava.rmi.server.codebase=file:/Users/franco/Desktop/prova/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
But the results are:
Trying to access code base: null
use is null
errore inizializzazione server
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub
I also try to public he jar on a local webserver xampp and try to run with the following:
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2/ -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
or with :
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
but I have the same results.
Try to set the classpath var before to execute the rmregistry:
export classpath="/Users/franco/Desktop/prova/"
rmiregistry 2005 &
There are three cases.
You got that exception in the server when exporting/constructing the remote object. Solution: run rmic to generate the stub.
You got it in the server when binding/rebinding. Solution: make the stub class available to the Registry's CLASSPATH, or run the Registry in the server JVM via LocateRegistry.createRegistry().
You got it in the client, in lookup(). Solution: make the stub class available to the client's CLASSPATH.
These also apply to the remote interface itself, and any application classes it depends on, and so on recursively until closure.
Solution for stubs to all three: take the measures outlined in the Javadoc preamble to UnicastRemoteObject, so you don't need a stub at all.

Load a jar in Java Class

I have a simple java class I want to load a jar file in my main method. How can I load the jar so that its available
public static void main(String args[]) throws SQLException, IOException{
String connectionString = "connectionstring";
File platformDB = new File(tempDir, "PlatformDB.eap");
createNewTempDirectory();
Mirror m = new Mirror(connectionString, createEmptyEap(emptyEapName) ,platformDB.getAbsolutePath());
m.run();
}
Mirror Class
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
}
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
}
}
In Mirror.run method I try to make a connection to database
Mirror.run() method
public void run() {
this.source = DriverManager.getConnection(EaDbStringParser.eaDbStringToJdbc(sourceString));
this.source.setReadOnly(true);
}
I have a jar file located under "C:\sqljdbc_4.0\enu\sqljdbc4.jar"
How can I load this jar so the connection is made successfully
Thanks
You just have to run the class with the -classpath option:
java -classpath C:\sqljdbc_4.0\enu\sqljdbc4.jar
The simplest way is to add the jar to the classpath loading the main class. For example if Mirror is the class with the main method where you say from console
`java Mirror'
modify it to
'java -cp C:/sqljdbc_4.0/enu/sqljdbc4.jar Mirror`

Run Non GUI Jar Files

I know that I can run non GUI jar files from the command line. Is there any way that can do so by clicking or something and not writing the commands again and again.? Is there any software to do so. ( I am talking about a compiled jar and don't want to run from any ide)
public static final String TITLE = "CONSOLE title";
public static final String FILENAME = "myjar.jar";
public static void main(String[] args) throws InterruptedException, IOException {
if(args.length==0 || !args[args.length-1].equals("terminal")) {
String[] command;
if(System.getProperty("os.name").toLowerCase().contains("win")) {
command = new String[]{"cmd", "/c", "start \"title \\\""+TITLE+"\\\" & java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
} else {
command =new String[]{"sh", "-c", "gnome-terminal -t \""+TITLE+"\" -x sh -c \"java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
}
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
} catch(Throwable t){
t.printStackTrace();
}
} else {
//THERE IS YOUR CONSOLE PROGRAM:
System.out.println("Hey! What's your name?");
String read = new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.println("Hey, "+read+"!");
Thread.sleep(10000);
}
}
You can run it with double clicking on .jar file. Don't forget about MANIFEST.MF! :) (working on linux, also!)
Example (I only double clicked on jar file):
The way intended by Java is that you call java -jar XXXX.jar on the jars you need. Drawback is that you can't specify a classpath so all classes should be there.
A cooler way to package an application is by using Java WebStart. With that the user installs the application jut by clicking on a web browser. Check here http://docs.oracle.com/javase/8/docs/technotes/guides/javaws/developersguide/contents.html

rmi java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub

I'm programming a simple rmi application, and I have a problem.
If I run the registry in the same directory, it works; but if I change the directory from which I run the registry, it does not.
The registry would work generically from another host, but only the change of directory stop his functionality.
I'm working on this problem by 3 days without solution, I change also every possible configuration of the codebase parameter but nothing.
I describe the situation and code with the directory:
fileserver.java :
`package testrmi2;
import java.rmi.*;
public interface fileserver extends Remote {
public void scrivifile(String nomefile, String arg) throws RemoteException;
}
`
fileserverimpl.java:
package testrmi2;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileserverimpl extends UnicastRemoteObject implements fileserver{
public fileserverimpl() throws RemoteException {
super();
}
public void scrivifile(String nomefile, String arg) throws RemoteException {
try {
FileWriter myfile = new FileWriter(nomefile);
myfile.write(arg);
myfile.close(); }
catch (Exception e) {System.out.println(e);}
}
public static void main (String arg[]) {
try {
fileserverimpl s = new fileserverimpl();
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String codebase = System.getProperty("classpath");
System.out.println("Trying to access code base: " + codebase+"\n\nuse is "+System.getProperty("useCodebaseOnly"));
Naming.rebind("//127.0.0.1:2005/fileserverimpl", s);
System.out.println("Server attivato.");
} catch (Exception e) {System.out.println("errore inizializzazione server\n\n"+e.getMessage()+"\n\n\n");
}}}
client.java:
package testrmi2;
import java.rmi.*;
import java.io.*;
public class client {
public static void main (String arg[]) {
fileserver myserver;
String nomefile=" ";
String testo=" ";
System.out.println("Scrivi il nome del file");
nomefile=ReadString();
System.out.println("Scrivi il testo");
testo=ReadString();
try {
myserver = (fileserver) Naming.lookup("//127.0.0.1:2005/fileserverimpl");
myserver.scrivifile(nomefile, testo);
} catch (Exception e) {System.out.println(e);}
}
public static String ReadString() {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));
String s=" ";
try{
s=stdIn.readLine();
}
catch(IOException e) {System.out.println(e.getMessage()); }
return s;
}
}
and the policy file is:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
all this files are on the directory:
/Users/franco/Desktop/prova
to compiling it I goes in the /Users/franco/Desktop/prova directory and do in terminal :
javac -cp . -d . *.java
rmic rmic testrmi2.fileserverimpl
jar cvf testrmi2.jar testrmi2/fileserver.class testrmi2/fileserverimpl_Stub.class
after I run registry in another terminal with the following commands but in another directory:
export classpath=""
rmiregistry 2005 &
Finally I would to run the filesereveimpl.class goes with terminal in the /Users/franco/Desktop/prova directory and write :
java -classpath /Users/franco/Desktop/prova/ -Djava.rmi.server.codebase=file:/Users/franco/Desktop/prova/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
But the results are:
Trying to access code base: null
use is null
errore inizializzazione server
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub
I also try to public he jar on a local webserver xampp and try to run with the following:
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2/ -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
or with :
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
but I have the same results.
Try to set the classpath var before to execute the rmregistry:
export classpath="/Users/franco/Desktop/prova/"
rmiregistry 2005 &
There are three cases.
You got that exception in the server when exporting/constructing the remote object. Solution: run rmic to generate the stub.
You got it in the server when binding/rebinding. Solution: make the stub class available to the Registry's CLASSPATH, or run the Registry in the server JVM via LocateRegistry.createRegistry().
You got it in the client, in lookup(). Solution: make the stub class available to the client's CLASSPATH.
These also apply to the remote interface itself, and any application classes it depends on, and so on recursively until closure.
Solution for stubs to all three: take the measures outlined in the Javadoc preamble to UnicastRemoteObject, so you don't need a stub at all.

Categories

Resources