如何从命令行执行 java .class [英] How to execute a java .class from the command line

查看:33
本文介绍了如何从命令行执行 java .class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编译好的java类:

I have a compiled java class:

Echo.class

public class Echo {
    public static void main (String arg) {

            System.out.println(arg);
    }
}

cd到目录并输入:java Echo "hello"

我收到此错误:

C:Documents and SettingsjoeMy DocumentsprojectsMiscin>java Echo "hello"
Exception in thread "main" java.lang.NoClassDefFoundError: Echo
Caused by: java.lang.ClassNotFoundException: Echo
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: Echo.  Program will exit.

以我可以从命令行运行的形式获取我的 java 代码的最简单方法是什么,而不必使用 Eclipse IDE?

What is the simplest way to get my java code in a form that I can run from the command line as apposed to having to use Eclipse IDE?

推荐答案

尝试:

java -cp . Echo "hello"

<小时>

假设你编译:


Assuming that you compiled with:

javac Echo.java 

然后有可能当前"目录不在您的类路径中(java 在其中查找 .class 定义)

Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )

如果是这种情况并列出目录显示的内容:

If that's the case and listing the contents of your dir displays:

Echo.java
Echo.class

那么任何一个都可以工作:

Then any of this may work:

java -cp . Echo "hello"

SET CLASSPATH=%CLASSPATH;.  

java Echo "hello"

后来作为 Fredrik 指出您将收到另一条错误消息,例如.

And later as Fredrik points out you'll get another error message like.

线程main"中的异常 java.lang.NoSuchMethodError: main

当这种情况发生时,去阅读他的回答:)

When that happens, go and read his answer :)

这篇关于如何从命令行执行 java .class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆