Could not load class when executed with -cp option

喜夏-厌秋 提交于 2019-12-14 02:33:40

问题


Java not able to find the class file when executed with -cp option as below

javac -cp ~/softwares/pig-0.12.0/pig-0.12.0.jar PR.java

Compilation is successful. However when I run the above generated class I am getting error

java -cp ~/softwares/pig-0.12.0/pig-0.12.0.jar PR
 Error: Could not find or load main class PR

If I remove the -cp I am getting below error which is expected

 java PR
 Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/pig/PigServer
    at PR.runPigScript(PR.java:9)
    at PR.main(PR.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.pig.PigServer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 2 more

Could you please let me what might be reasons for failure is Step-2(Could not find or load main class) . Below is the code of PR.java

  import org.apache.pig.ExecType;
  import org.apache.pig.PigServer;
  import org.apache.pig.backend.executionengine.ExecException;

 public class PR {

    public void runPigScript(){
            try {
                    PigServer  pigServer = new PigServer(ExecType.LOCAL);
                    pigServer.registerScript("RP.pig");
            } catch (Exception ex) {
                    // TODO Auto-generated catch block
                    ex.printStackTrace();
            }
    }

  public static void main(String[] args){
      PR pr = new PR();
     pr.runPigScript();
  }

}

From https://wiki.apache.org/pig/EmbeddedPig

To run your program, you need to first compile it by using the following command:

   javac -cp <path>pig.jar WordCount.java

If the compilation is successful, you can then run your program:

   java -cp <path>pig.jar WordCount

回答1:


Try to use:

java -cp ~/softwares/pig-0.12.0/pig-0.12.0.jar;. PR

The problem is that you need to load your compiled PR class as well. So your classpath needs to have both dependencies and your compiled output. Add current directory to the classpath.



来源:https://stackoverflow.com/questions/23077064/could-not-load-class-when-executed-with-cp-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!