This question already has an answer here:
Error when trying to execute a command in java [duplicate]
(1 answer)
Closed 9 years ago.
I want to run java file using 'java filename' command when you're not in the file's directly.
In the terminal we use :
cd filepath
java filename
but in Eclipse you cannot change the directory using 'cd' so how can I run the file although I can't change the directory
I am using this method to run a command using Java
try {
String line;
Process p = Runtime.getRuntime().exec( "cd /Users/apple/Documents/Documents/workspace/UserTesting/src" );
Process p2 = Runtime.getRuntime().exec( "java NewFile" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p2.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (Exception e) {
// ...
}
Here are several trials
Apples-MacBook-Pro:~ apple$ cd
/Users/apple/Documents/Documents/workspace/UserTesting/src
Apples-MacBook-Pro:src apple$ java NewFile 5 90 35 45 150 3
Reichweite---- nach blase art
3 5 35 45 90 150
Apples-MacBook-Pro:src apple$ java /Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile
Exception in thread "main" java.lang.NoClassDefFoundError:
/Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile
Caused by: java.lang.ClassNotFoundException:
.Users.apple.Documents.Documents.workspace.UserTesting.src.NewFile at
java.net.URLClassLoader$1.run(URLClassLoader.java:202) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:190) at
java.lang.ClassLoader.loadClass(ClassLoader.java:306) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Apples-MacBook-Pro:src apple$ java
/Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile.java
Exception in thread "main" java.lang.NoClassDefFoundError:
/Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile/java
Caused by: java.lang.ClassNotFoundException:
.Users.apple.Documents.Documents.workspace.UserTesting.src.NewFile.java
at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:190) at
java.lang.ClassLoader.loadClass(ClassLoader.java:306) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Apples-MacBook-Pro:src apple$
Blockquote
This will not work.
For one, cd is a shell command. And then you create another process to run the java command.
You need a ProcessBuilder. You can set up the initial directory, environment etc:
final File wantedCwd = new File(...);
final ProcessBuilder pb = new ProcessBuilder("java", "thefile");
// Change directory
pb.directory(wantedCwd);
You can even change the stdin, stdout, stderr etc of the command.
DO NOT use Runtime.exec(). It won't (exec()) in many situations.
Related
I am working on a project that is going to do serial communication and I want to package the java-simple-serial-connector (jssc) as part of the project.
I don't want to install the jssc.jar file on the system because this project is going to be run a bunch of different machines so it would be much easier to package the .jar with my executable .jar.
I have added jssc.jar to my build path but when I run the program (note it isn't finished yet) I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: SerialCommunication
Caused by: java.lang.ClassNotFoundException: SerialCommunication
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Here is my code
import jssc.*;
public class SerialCommunication {
public static void main(String[] args) {
String[] portNames;
if(System.getProperty("os.name").equals("Mac OS X")){
portNames = SerialPortList.getPortNames("/dev/");
System.out.println("OS X");
} else {
portNames = SerialPortList.getPortNames("COM");
System.out.println("Windows");
}
for (int i = 0; i < portNames.length; i++) {
System.out.println(portNames[i]);
}
SerialPort serialPort = new SerialPort(portNames[0]);
try {
serialPort.openPort();// Open serial port
serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.writeBytes("This is a test string".getBytes());
serialPort.closePort();// Close serial port
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
Under the build path I added the jssc.jar as a library and as an external library. Both of them fail in the same way. I have also cleaned the solution.
EDIT:
My file structure is the following
/src
SerialCommunication.java
/lib
jssc.jar
Here is my build path
How do I get the program to execute properly with the jssc.jar in the path?
Is the JRE you are using for running the program >= than the JDK with which jssc.jar was compiled?
This question already has answers here:
How to use "cd" command using Java runtime?
(8 answers)
Closed 9 years ago.
I am trying to run a java file using the terminal but from java. Meaning, I'll run the command using java.
I am trying to execute the command 'cd /Users/apple/Documents/Documents/workspace/UserTesting/src ' that redirects to the following directory and then execute the command 'ls' that lists all the files in the current directory
I am using this method to run the Java file 'NewFile.java'
try {
String line;
Process p = Runtime.getRuntime().exec( "cd /Users/apple/Documents/Documents/workspace/UserTesting/src" );
Process p2 = Runtime.getRuntime().exec( "ls" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p2.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (Exception e) {
// ...
}
The output
Directly using the terminal -> It gives 'NewFile.java'
Using this method using Java -> It always give 'bin' and 'src' for whatever command given to p2
Here are several trials
Apples-MacBook-Pro:~ apple$ cd
/Users/apple/Documents/Documents/workspace/UserTesting/src
Apples-MacBook-Pro:src apple$ java NewFile 5 90 35 45 150 3
Reichweite---- nach blase art
3 5 35 45 90 150
Apples-MacBook-Pro:src apple$ java /Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile
Exception in thread "main" java.lang.NoClassDefFoundError:
/Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile
Caused by: java.lang.ClassNotFoundException:
.Users.apple.Documents.Documents.workspace.UserTesting.src.NewFile at
java.net.URLClassLoader$1.run(URLClassLoader.java:202) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:190) at
java.lang.ClassLoader.loadClass(ClassLoader.java:306) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Apples-MacBook-Pro:src apple$ java
/Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile.java
Exception in thread "main" java.lang.NoClassDefFoundError:
/Users/apple/Documents/Documents/workspace/UserTesting/src/NewFile/java
Caused by: java.lang.ClassNotFoundException:
.Users.apple.Documents.Documents.workspace.UserTesting.src.NewFile.java
at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:190) at
java.lang.ClassLoader.loadClass(ClassLoader.java:306) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Apples-MacBook-Pro:src apple$
Blockquote
So, it seems the problem you're having is that you don't understand why you get different results when you invoke the program in different ways.
Here's what's going on: Runtime.geRuntime().exec() creates a new process, which is a child of the parent. Every process has its own working directory; when you fork a new process, it inherits the working directory of the parent. Invoking cd will then change the working directory of the current process (and this is a shell builtin, but ignore that for now and I'll get to it later).
So what you're doing is this:
Parent
-> create child 1 -> change working directory of child 1
-> create child 2 -> invoke "ls"
Note that child 2 will inherit the working directory of its parent. It won't know anything about the working directory of child 1. So depending on the working directory of the process that is invoking this method (in your case, either the terminal or...I don't know, your JDK install?) you will get different results.
If you want the same results every time, you could do something like this:
Process p = Runtime.getRuntime().exec( "ls /Users/apple/Documents/Documents/workspace/UserTesting/src" );
And if you want to be able to exec your program from anywhere, just use the full path:
Process p = Runtime.getRuntime().exec( "java /Users/apple/Documents/Documents/workspace/UserTesting/NewFile" );
(assuming, of course, that you have already used javac to build NewFile.class in that directory, and that you have the right permissions to execute it.)
Re: cd, as I mentioned before this is a command that's built into your shell. When you invoke the command using exec in this way, it is likely failing. You can check on that by reading standard error using the getErrorStream() method of Process.
I wrote a simple java program
package abc.def.ghi
public class Foobar{
public String printS(String s){
System.Out.println(s);
public static void main(String [] args){
String s = args[0];
Foobar foobar = new Foobar();
foobar.printS(s);
}
Now I did javac Foobar.java
It created a class file
and then I did
java Foobar
Didnt worked
java Foobar hi //args
Didnt worked
java -cp . abc.def.ghi.Main
DIdnt worked.
Error I am getting is:
Exception in thread "main" java.lang.NoClassDefFoundError: abc/def/ghi/Main
Caused by: java.lang.ClassNotFoundException: com.intel.hadoop.graphbuilder.conf.Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.intel.hadoop.graphbuilder.conf.Main. Program will exit.
Did you put your .class files in the path (path to project)/abc/def/ghi/Foobar.class?
NoClassDefFoundError: abc/def/ghi/Foobar
Looks like you didn't.
If you compile using
javac -d . Foobar.java
then the compiler will put the .class file in the right directory to match its package name, then
java abc.def.ghi.Foobar
should run it successfully.
I am new to pig.. and am trying to write a udf function.
So basically here is the problem statement.
I have a dummy data like this..
user_id, movie_id, date_time_stamp
So what I am trying to do is this.
if the transaction is between
9 am and 11 am --> breakfast
and so on
So here is my pig script
REGISTER path/myudfs.jar
in = LOAD 'path/input' USING
PigStorage('\\u001') AS (user:long,movie:long, time:chararray);
result = foreach in GENERATE myudfs.time(time);
STORE result INTO 'path/output/time' using PigStorage(',');
Now myudf.jar java code is like this
public class time extends EvalFunc<String>{
public String exec(Tuple input) throws IOException {
if ((input == null) || (input.size() == 0))
return null;
try{
String time = (String) input.get(0) ;
DateFormat df = new SimpleDateFormat("hh:mm:ss.000");
Date date = df.parse(time);
String timeOfDay = getTimeOfDay(date);
return timeOfDay;
} catch (ParseException e) {
//how will I handle when df.parse(time) fails and throws ParseException?
//maybe:
return null;
}
}
So it takes in the tuple and returns a string... (I am new to java also..)
After this i try to run this script as
pig -f time.pig
It returns an error
2012-11-12 08:33:08,214 [main] INFO
org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to
hadoop file system at: maprfs:///
2012-11-12 08:33:08,353 [main] INFO
org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to
map-reduce job tracker at: maprfs:///
2012-11-12 08:33:08,767 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1069:
Problem resolving class version numbers for class myudfs.time
Some one posted on pig mailing list is that my PIG_CLASSPATH is not set and that i should point it to /path/hadoop/conf
I did that.. so now $echo PIG_CLASSPATH --> /path/hadoop/conf
But i get the same error
Please advise.
Thanks
Edit 1: On looking into the log, the error trace is:
Caused by: java.lang.UnsupportedClassVersionError: myudfs/time : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.apache.pig.impl.PigContext.resolveClassName(PigContext.java:427)
... 27 more
is this like a java issue?
To find the jar version, open the jar using winzip (or similar) and look for manifest.mf. There should be a line in there that says 'Created-By' and this will give the version of java that was used to build the jar.
This needs to be older or equal to the version of java you are using to build your app. If you are doing this at the command line type:
java -version
or in eclipse go to
project(menu) > properties (menu item) > java build path (in list) > libraries (tab)
and take a look at the version that you are using for the JDK/JRE (you may be able to tell this from the directory, if not then go to that directory and do java -version).
Chances are you'll need to update the version of java you have in eclipse.
I am attempting to run the following Java code on an Ubuntu system. The code should create a blank PDF file using the pdfbox class:
import org.apache.pdfbox.pdmodel.*;
import java.io.*;
public class BlankPDF {
public static void main(String[] args) {
PDDocument doc = null;
try{
doc = new PDDocument();
} catch (IOException ie){
System.out.println(ie);
}
doc.addPage(new PDPage());
try{
doc.save("Empty PDF.pdf");
doc.close();
} catch (Exception io){
System.out.println(io);
}
}
}
I have the following class dependencies in the same directory as the script:
pdfbox-1.7.0.jar
jempbox-1.7.0.jar
fontbox-1.7.0.jar
commons-logging-1.1.1.jar
I used the following command to compile the script:
sudo javac BlankPDF.java -classpath pdfbox-1.7.0.jar:fontbox-1.7.0.jar:jempbox-1.7.0.jar:commons-logging-1.1.1.jar
Which returned no output and created a .class file (indicating that the compilation worked correctly?)
But when I attempt to run the code using the following command:
sudo java BlankPDF -classpath pdfbox-1.7.0.jar:fontbox-1.7.0.jar:jempbox-1.7.0.jar:commons-logging-1.1.1.jar
I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/pdfbox/pdmodel/PDDocument
at BlankPDF.main(BlankPDF.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.pdfbox.pdmodel.PDDocument
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
... 1 more
What am I missing?
The name of the class must be the last argument to java. The flags must precede it. If you put flags at the end of the command lines, as here, they are ignored. So:
java -classpath .:pdfbox-1.7.0.jar:fontbox-1.7.0.jar:jempbox-1.7.0.jar:commons-logging-1.1.1.jar BlankPDF
With ref to above answer,don't forget to add current directory (with dot sign) as well in command with jars in classpath
java -classpath hello.jar:. SampleProgram