How to execute 'cd' command and then a linux command in java - java

I have directory /tmp
then I need to execute cd and go to that folder.
Then I need to execute ./executeScript

Preparation
To start solving the problem, I created a directory /home/vulpini99/tmp. In this directory, I created the bash-script test.sh, which will open firefox for us:
firefox
Then I created a java-file named LinuxCommand.java in the directory /home/vulpini99.
Main part
cd is just an internal shell command and not an executable program, so I suggest to just use the full path of the bash-script. So the command we want to execute is
bash /home/vulpini99/tmp/test.sh.
In Java, you can use Runtime for this purpose:
import java.io.IOException;
public class LinuxCommand {
public static void main(String[] args) {
Runtime run = Runtime.getRuntime();
try {
run.exec("bash /home/vulpini99/tmp/test.sh");
}
catch(IOException e) {
e.printStackTrace();
}
}
}

Related

Running .JAR file from java code (netbeans)

Im trying to run a jar file from java code, But unfortunately does not success.
A few details about the jar file:
The jar file located in a different folder (For example - "Folder").
The jar file using a files and folders are in the root folder (the same "Folder" i mentioned above).
What im trying to do so far:
JAR file project.
In netbeans i checked that the main class are defiend (Project properties -> Run -> Main Class).
Other JAVA program
Trying to run with the command:
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar");
&&
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar" "C:\\Software");
The jar file opened well, But he doesnt know and recognize his inner folders and files (the same "Folder" i mention above).
In short, it does not recognize its root folder.
Trying to run with ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start", "javaw", "-jar", "C:\\Software\\program.jar");
pb.directory(new File("C:\\Software"));
try {
pb.start();
} catch (IOException ex) {
}
In Some PC's its works fine, But in other pc's its not work and i got an error message: "Could not find the main class"
** Offcourse if i run the jar with double click its works.
So how can i run a jar file from other java program ?
Use this variant of .exec where you specify working folder as the third argument. (In your examples, you always only use one argument.)
exec("javaw -jar "C:\\Software\\program.jar", null, "C:\\Software");
You can try to call it something like below. There are 2 types of calling it.
public class JarExecutor {
public static void main(String[] args) throws IOException, InterruptedException {
//This is first way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-jar" ,"C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar"});
//This is second way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-cp","C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar","com.shiva.practise.FloydTriangle"});
proc.waitFor();
BufferedInputStream is=new BufferedInputStream(proc.getInputStream());
byte[] byt=new byte[is.available()];
is.read(byt,0,byt.length);
System.out.println(new String(byt));
}
}

Running java class with library from cmd

I have a Baseloader.java class which makes use of Postgresql database, and I have a postgresql42.jar file which handles the jdbc stuff.
Baseloader.java
import java.sql.Connection;
import java.sql.DriverManager;
public class Baseloader
{
public static void main(String[] args)
{
System.out.println("Hello, sir!");
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/my_base",
"postgres", "123");
System.out.println("Done, sir!");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
So, when I compile and run this code through Netbeans (the postgresql.jar was included using GUI into Libraries folder) everything goes OK, the output is
Hello, sir!
Done, sir!
Opened database successfully
But when I try to run the compiled class file from cmd I get an error.
I placed Baseloader.class and postgresql42.jar into the same folder and cd'ed into that folder in cmd. Then I use the java -classpath postgresql42.jar Baserunner command which was proposed on one of the answers here, but it gava me Could not find or load main class Baseloader error.
If I type just java Baseloader it gives Exception in thread "main" java.lang.UnsupportedClassVersionError.
What I'm doing wrong and how to fix it?
EDIT: I've changed the java version in cmd: now java -version gives 1.8.0_73'.Then I checked which version Netbeans used: System.out.println(System.getProperty("java.version")) it also gave 1.8.0_73.
In environmental variables the JAVA_HOME is C:\Program Files\Java\jdk1.8.0_73, while System.out.println(System.getProperty("java.home")) gives C:\Program Files\Java\jdk1.8.0_73\jre. Can that difference be the case?
EDIT2: Changed JAVA_HOME to C:\Program Files\Java\jdk1.8.0_73\jre with no result.
Also javac -version gives the same newest 1.8.0_73 now.

JavaFX - Virtual Keyboard Doesn't Show When the App Jar is Generated

I have created a JavaFX application in IntelliJ14.14 that will use the JavaFX Virtual Keyboard. I have add the following properties in the mainApp class controller:
public static void main(String[] args) {
System.setProperty("com.sun.javafx.isEmbedded", "true");
System.setProperty("com.sun.javafx.touch", "true");
System.setProperty("com.sun.javafx.virtualKeyboard", "javafx");
launch(args);
}
When I run the app from IntelliJ everything works fine. The virtual keyboard works perfectly.
But when I generate the Jar file of the application from Build -> Build Artifacts... -> Build and execute it, the keyboard never shows because the VM options are not being set.
It's something I'm missing...?
Thanks in advance...
EDIT
I have found a way to make this work, running the file from the cmd with this command:
java -Dcom.sun.javafx.isEmbedded=true -Dcom.sun.javafx.virtualKeyboard="javafx" -Dcom.sun.javafx.touch=true -jar myApp.jar
However I want to make this just executing the Jar file...
EDIT
There is another nearby way to accomplish what I want...
Create a file .bat in the same folder of the jar and put in it:
start javaw -Dcom.sun.javafx.isEmbedded=true -Dcom.sun.javafx.virtualKeyboard="javafx" -Dcom.sun.javafx.touch=true -jar myApp.jar
So when tha .bat file is executed and the jar file is started, the system properties are loaded correctly...
public class MyApp {
public static void main(String[] args) {
if (args.length == 0) {
try {
// re-launch the app itselft with VM option passed
Runtime.getRuntime().exec(new String[] {"java", "-Dcom.sun.javafx.isEmbedded=true", "-Dcom.sun.javafx.virtualKeyboard=\"javafx\"", "-Dcom.sun.javafx.touch=true", "-jar", "myApp.jar"});
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.exit(0);
}
// Run the main program with the VM option set
//...
//...
}
}

NoClassDefFoundError - could not initialize class ...?

I am getting an error while writing my simple test program:
package Xbee;
import com.rapplogic.xbee.api.XBee;
import com.rapplogic.xbee.api.XBeeException;
public class XbeeTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
XBee xbee = new XBee();
try {
xbee.open("COM22", 9600);
} catch (XBeeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am getting the following:
java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class gnu.io.RXTXVersion
at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:123)
at com.rapplogic.xbee.RxTxSerialComm.openSerialPort(RxTxSerialComm.java:71)
at com.rapplogic.xbee.RxTxSerialComm.openSerialPort(RxTxSerialComm.java:61)
at com.rapplogic.xbee.api.XBee.open(XBee.java:140)
at Xbee.XbeeTest.main(XbeeTest.java:14)
The whole problem is that it cannot initialize the class gnu.io.RXTXversion, which is a prt of rtxtcomm.jar, which I have included in my Maven dependency:
<dependency>
<groupId>org.bidib.jbidib.org.qbang.rxtx</groupId>
<artifactId>rxtxcomm</artifactId>
<version>2.2</version>
</dependency>
Any ideas? Thanks.
As I previously mention in comment, you need also native library to make it work. Put it in ${JRE_HOME}/lib/i386
nice article: http://pharos.ece.utexas.edu/wiki/index.php/How_to_Access_Your_Serial_Port_using_Java
and quote from article:
$ wget http://rxtx.qbang.org/pub/rxtx/rxtx-2.1-7-bins-r2.zip
Unzip the rxtx archive and install it. The following commands assume
your JVM is located in /usr/lib/jvm/java-6-openjdk/ and that you are
using a 32-bit x86 computer. You will need to slightly modify these
commands if you have a different JVM or system architecture (i.e.,
64-bit).
$ sudo apt-get install zip
$ unzip rxtx-2.1-7-bins-r2.zip
$ cd rxtx-2.1-7-bins-r2
$ sudo cp RXTXcomm.jar /usr/lib/jvm/java-6-openjdk/jre/lib/ext/
$ sudo cp Linux/i686-unknown-linux-gnu/librxtx* /usr/lib/jvm/java-6-openjdk/jre/lib/i386/
Java Build Path -> Source -> Native library location -> Add your rxtxso and Comm jar file.
Java Build Path -> Add External JAR -> RXTXcomm.jar
Java Build Path -> Order and Export -> Click RXTXcomm.jar

package oracle.jdbc.driver does not exist

Error in the following code ![error occured][1]
import java.sql.*;
public class DBConnect{
public static void main(String a[]) throws SQLException{
// *package oracle.jdbc.driver does not exist*
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
System.out.println("Driver is registered");
}
}
You have to add ocjdbc jar in to your class path and try it like this.
if your jar file and java source is in same location. Use a command prompt and changed directory to that location. and execute following
javac -classpath ocjdbc14.jar DBConnect.java
and see.
import java.sql.*;
import oracle.jdbc.driver.OracleDriver;
public class DBConnect{
public static void main(String a[]) {
try{
Driver d=new OracleDriver();
DriverManager.registerDriver(d);
System.out.println("Driver is registered");
}catch(SQLException e){
System.out.println("Error occured "+e.getMessage());
}
}
}
You need to Add an oracle driver jar to the project build path,
Download Ojdbc14.jar file and put it in your classpath.
You need to do following steps if you are using intellij
Download jdbc7 or any version
Add this jar on following path File>>Project Structure>>Libraries>>
Image 1
Click on Modules and add jar there too
if you still face issue then you must see following problem
Image 2
Now click on problems>>fix>>add to dependency as given below
Image 3
Hope this will fix your issue
First run the program in netbeans and add Ojdbc14.jar file into the library of the program and then it will surely execute.
After executing in NetBeans, click Clean & Build Project.... This will create a jar file and then path like
java -jar "C:\Users\s\Documents\NetBeansProjects\jdbcTest_course\dist\jdbcTest_course.jar" will be provided.
Enter this into a command prompt (cmd) and it will run.

Categories