简体   繁体   English

从命令行运行Java代码

[英]Java running code from command line

I'm on Mac OS X 10.9.2 (Mavericks). 我在Mac OS X 10.9.2(Mavericks)上。 I have code that uses an external Java library (twitter4j). 我有使用外部Java库(twitter4j)的代码。 It runs fine when I run it through NetBeans. 当我通过NetBeans运行它时,它运行良好。 However, trying to run almost identical code in the terminal gives me errors. 但是,尝试在终端中运行几乎相同的代码会给我错误。

My directory structure is straightforward- I have a 'src' folder with the .java file and a 'lib' folder with the external .jar files I use. 我的目录结构很简单-我有一个带有.java文件的'src'文件夹和一个我使用的外部.jar文件的'lib'文件夹。

From the src folder, I call javac -cp "../lib/*" MyProgram.java which seems to work alright. 从src文件夹中,我将javac -cp "../lib/*" MyProgram.java称为javac -cp "../lib/*" MyProgram.java ,它似乎可以正常工作。 Now, if I call java MyProgram , I get an exception: 现在,如果我调用java MyProgram ,则会出现异常:

Exception in thread "main" java.lang.NoClassDefFoundError: twitter4j/StreamListener
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2693)
at java.lang.Class.privateGetMethodRecursive(Class.java:3040)
at java.lang.Class.getMethod0(Class.java:3010)
at java.lang.Class.getMethod(Class.java:1776)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: twitter4j.StreamListener
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

It seems to have trouble properly importing the external twitter4j library. 似乎无法正确导入外部twitter4j库。 What am I missing here? 我在这里想念什么?

These are my import statements in the code: import twitter4j.*; 这些是我在代码中的导入语句: import twitter4j.*; , import twitter4j.conf.ConfigurationBuilder; import twitter4j.conf.ConfigurationBuilder;

UPDATE: Using suggestions below, I also tried running it via java -cp "../lib/*" MyProgram which gives: "Could not find or load main class MyProgram" 更新:使用下面的建议,我还尝试通过java -cp "../lib/*" MyProgram运行它,它给出:“找不到或加载主类MyProgram”

You need to specify the classpath when running the program as well as when compiling it: 在运行程序以及进行编译时,您需要指定类路径:

Eg 例如

java -cp "../lib/*" MyProgram

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM