java mysterious classpath behavior - java

I failed specifying the class path. Here's my setup:
File: "root/src/hello/German.java"
package hello;
public class German {
public void greet() { System.out.println("Hallo"); }
}
I compile this in "root":
> javac root/src/hello/German.java -d root/package
where "root/package/hello" exists as an empty directory. Fine. Now I want to test and write
File: "root/test/testHello.java"
import hello.German;
public class helloTest {
public static void main(String[] args) {
German guy = new German();
guy.greet();
}
}
I compile
> javac testHello.java -cp ../package
To summarize, I have:
root/package/hello/German.class
root/test/helloTest.class
I execute in "root/test/":
> java testHello => class not found except.
> java testHello -cp ../package => class not found except.
> java testHello -cp ../package/hello => class not found except.
However, copying the 'hello' directory into test such that there is
root/test/hello/German.class
root/test/helloTest.class
I can execute in "root/test/"
> java testHello
and it greets friendly in German. I want to specify the classpath, though. But, I have no idea why '-cp' and '-classpath' is not accepted.

Try this:
java -classpath .:../package testHello
.:../package to use the current directory and ../package as classpath.

Related

Compile .java file with external dependecy into .class file

I have the following External.java file that has an external dependency on JAsioHost.jar file placed in folderWhereMyJarIs:
package external;
import com.synthbot.jasiohost.*;
public class External {
public External(){
System.out.println("Class CONSTRUCTOR");
}
public int operateAdd(int a, int b){
int res = a+b;
return res;
}
public static void main(String[] args) {
System.out.println("Hello world");
}
}
I am having trouble compiling the .java file into .class file from my Windows command line because when I type
javac -cp .;/folderWhereMyJarIs/JAsioHost.jar External.java
it gives me the following error:
package com.synthbot.jasiohost does not exist
What am I doing wrong?
As suggested by #shadowsheep in his helpful comment, I answer my own question posting the solution that works just fine:
javac -cp .;./folderWhereMyJarIs/JAsioHost.jar External.java
Hope this will help others

How to get path to class file in eclipse and linux in java?

In eclipse for windows, when I run
public class HelloWorld {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
}
}
It gives me the path of the project root folder (which contains the bin folder which has the class file). For example
SampleProject
and the class file is actually located at
SampleProject\bin\myclass.class
But if I run the same program in linux with
javac myclass.java
java myclass
it gives me the directory that has the .class file, which is the same as pwd command. This is what I want in eclipse for windows. I want some code that will give me the path to the class file in both eclipse for windows and linux.
Does anyone know how do this?
Thanks
If I understand you correctly, you'd like a method that retrieves a class' path on disk. This is easily achievable, like so:
public String getClassPath(Class c) {
try {
return c.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
NOTE this will work even if the class is contained in a jar file. It will return the path to the jar in this case.
The easiest way is to do this:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(HelloWorld.class.getResource("HelloWorld.class"));
}
}

How to call a class from another in th same package shows an error how to fix it in java?

How to call a class from another in th same package shows an error how to fix it?
i have three classes
FirstPack.java
SecondPack.java
Main.java
Here is my FirstPack.java
//FirstPack.java
package mypack.in;
public class FirstPack
{
public void fun()
{
try
{
System.out.println("First Package");
}
catch(Exception ae)
{
}
}
}
Here is my SecondPack.java
//SecondPack.java
package mypack.in;
public class SecondPack
{
public void fun()
{
FirstPack f=new FirstPack();
f.fun();
try
{
System.out.println("Second Package");
}
catch(Exception ae)
{
}
}
}
Here is my Main.java
//Main.java
import java.lang.*;
import mypack.in.*;
class Main
{
public static void main(String args[])
{
try
{
//FirstPack obj_fp=new FirstPack();
//obj_fp.fun();
SecondPack obj_sp=new SecondPack();
obj_sp.fun();
}
catch(Exception ae)
{
}
}
}
On compiling Firstpack.java ie javac FirstPack.java - no problem
On compiling SecondPack.java ie javac SecondPack.java- Error ....
C:\JAVASAMPLE\Package\Three\mypack\in>javac SecondPack.java
SecondPack.java:7: cannot find symbol
symbol : class FirstPack
location: class mypack.in.SecondPack
FirstPack f=new FirstPack();
^
SecondPack.java:7: cannot find symbol
symbol : class FirstPack
location: class mypack.in.SecondPack
FirstPack f=new FirstPack();
^
2 errors
And, on compiling Main.java ie javac Main.java - no problem
Package - mypack.in FirstPack.java and SecondPack.java Outside mypack.in Main.java Sir if without package yes it workinf but with pakage it didnt working I am not using any IDEs
[EDIT]
Note, you should not be compiling each class independently. The Java compiler is designed to compile each class as it encounters the first instance of it in your source file. Compile your Main.java from the root directory, and you won't have any errors.
[/EDIT]
[SECOND EDIT]
I believe this is all happening because the javac compiler begins looking for classes in the current directory and then searches through sub-directories. Since FirstPack is part of the mypack.in package, it needs to be in a folder ./mypack/in/ beginning from the current directory (the directory you execute the compiler from. Basically, your compiler knows that FirstPack is actually mypack.in.FirstPack and will begin looking for ./mypack/in/FirstPack from wherever the file you are trying to compile is residing.
http://kevinboone.net/classpath.html
[/SECOND EDIT]
Although it is throwing an error on compilation, this program is executing properly for me. Ensure that Main.class is in the root directory, and that FirstPack and SecondPack are in %root%\mypack\in
I can't tell you exactly why all of this is the way it is, but I know it's working this way.
You can do it like this:
///**Import the Package
import mypack.in.FirstPack;

exception in thread"main"java.lang.NoClassDefFoundError:

package p1;
public class test_package{
public void show(){
System.out.println("package1");
}
public static void main(String args[]){
test_package t=new test_package();
t.show();
}
}
Here is the first class made that has been compiled and package is saved in D: directory...it is running well...
now...
package p2;
import p1.test_package;
public class test_package2{
public void show(){
System.out.println("package2 in c:");
}
public static void main(String args[]){
test_package2 T=new test_package2();
test_package T1=new test_package();
T.show();
T1.show();
}
}
here is another class importing first class and this is saved in C: directory...
i have set temperory path using cmd command
set classpath=D:
and compiled it from C: using command
javac -d C: test_package2.java
when i am running it by command from C:
java p2.test_package2
it is throwing the error
exception in thread "main" java.lang.NoClassDefFoundError
but the .class file is in p1 package that is in D: drive.....
please help me if anyone has the solution.
It's because JVM is not able to find the test_package in the class_path of test_package2 which is D:. Add test_package to the build path of test_package2. In eclipse you can do this by Right-click on test_package2 > Build Path > Configure Build Path > Add External Class Folder (or you can zip test_package and use as an external library as well). Now import it in test_package2. It should run.

Why can't java find my class?

I have a class that compiles without error. The class has a main method. But when I try to run it on ubuntu linux from the classes' directory I get a class not found error. I am pretty sure I am missing something dead obvious but I don't see it.
Here is my ls operation:
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ ls
CreateGroup.java LsGroup.class LsGroup.java zookeeper-3.4.5.jar
Here is what happens when I to run LsGroup
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ java -cp "zookeeper-3.4.5.jar" LsGroup
Exception in thread "main" java.lang.NoClassDefFoundError: LsGroup
Caused by: java.lang.ClassNotFoundException: LsGroup
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)
Could not find the main class: LsGroup. Program will exit.
Here is the code for LsGroup
package org.zookeeper;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class LsGroup implements Watcher {
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zk;
private CountDownLatch connectedSignal = new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}
#Override
public void process(WatchedEvent event) { // Watcher interface
if (event.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
public void ls(String groupName) throws KeeperException, InterruptedException {
String path = "/" + groupName;
try {
List<String> children = zk.getChildren(path, false);
for (String child : children) {
System.out.println(path+"/"+child);
System.out.println(zk.getChildren(path +"/"+ child, false));
}
} catch (KeeperException.NoNodeException e) {
System.out.printf("Group %s does not exist\n", groupName);
System.exit(1);
}
}
public void close() throws InterruptedException {
zk.close();
}
public static void main(String[] args) throws Exception {
LsGroup lsGroup = new LsGroup();
lsGroup.connect(args[0]);
lsGroup.ls(args[1]);
lsGroup.close();
}
}
The original problem was that your class was in a package, but you were trying to load it as if it weren't in a package. You'd normally organize your source code to match your package hierarchy, then from the root of the hierarchy, you'd run something like:
java -cp .:zookeeper-3.4.5.jar org.zookeeper.LsGroup
Now that you've temporarily worked around the package issue by moving the code out of a package, the next problem is that the current directory isn't in the classpath. So instead of this:
java -cp "zookeeper-3.4.5.jar" LsGroup
You want:
java -cp .:zookeeper-3.4.5.jar LsGroup
Once you've got that working, you should move the classes back into packages, as per normal Java best practice.
You could remove the package declaration:
package org.zookeeper;
...or just place your LsGroup class in org/zookeeper directory.
The class file is supposed to live in a path like:
org/zookeeper/LsGroup.class
The -cp must include the directory that contains the org/ directory. Then you can
java -cp parent-of-org org.zookeeper.LsGroup
The message "wrong name: org/zookeeper/LsGroup" means, you have to respect the package structure of Java. Use the following directory structure:
./org/zookeeper/LsGroup.class
Then launch java org.zookeeper.LsGroup from within the current directory. The package separator "." will be translated to corresponding directory.
Your files are not under package org.zookeeper
You should be running your class from ~/zookeeper-3.4.5/org/zookeeper
Otherwise JVM won't find the classes to load.
Your class is part of the org.zookeeper package but you keep it in the root folder of your project (/zookeeper-3.4.5/programs).
The qualified name of the package member and the path name to the file are parallel (see Managing Source and Class Files), so if your package is org.zookeeper the class file should be kept in /zookeeper-3.4.5/programs/org/zookeeper
You made two mistakes:
1) You tried to run java LsGroup but you have to use the complete name including packages java org.zookeeper.LsGroup
2) your directory structure is not correct: the package org.zookeeper corresponds with the directory structure ./org/zookeeper/
If you change the directory structure and then run java from the top of this directory structure it should work

Categories

Resources