如何在 Java 中编译 .java 文件? [英] How to compile a .java file in Java?

查看:21
本文介绍了如何在 Java 中编译 .java 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下由 Eclipse 生成的代码(.java 文件).

I have the following code generated by Eclipse (.java file).

import org.eclipse.swt.widgets.Shell;

import org.eclipse.swt.widgets.Display;

public class HelloWorldSWT {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("Hello world!");
        shell.open();
        while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
    }

}

现在我想从命令行编译上面的文件.我去了源代码所在的目录,我尝试了两个命令:
1.javac HelloWorldSWT.java
2.javac -d/home/myname/workspace/HelloWorldSWT.java

Now I want to compile the above file from the command line. I went to the directory where the source code is located and I tried two commands:
1. javac HelloWorldSWT.java
2. javac -d /home/myname/workspace/ HelloWorldSWT.java

在这两种情况下,我都有相同的错误无法解析导入 org.eclipse"./home/myname/workspace/- 是类文件所在的目录.

In both cases I have the same error "The import org.eclipse cannot be resolved". /home/myname/workspace/ - is the directory where the class file is located.

据我所知,编译器没有看到 org.eclipse.swt 包.为什么?

As far as I understand the compiler does not see the org.eclipse.swt package. Why?

可能是因为有问题的包位于/home/myname/workspace/org.eclipse.swt/"(而不是/home/myname/workspace/org/eclipse/swt/")?

Can it be because the problematic package is located in "/home/myname/workspace/org.eclipse.swt/" (not in "/home/myname/workspace/org/eclipse/swt/")?

推荐答案

您需要设置类路径,以便 Java 编译器知道在哪里可以找到 org.eclipse.* 类.您可以使用命令行开关或环境变量来实现.

You need to set your classpath so that the Java compiler knows where to find the org.eclipse.* classes. You can do that with a command line switch or an environment variable.

这篇关于如何在 Java 中编译 .java 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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