如何在包中编译类,以便稍后使用“java Program”执行它们。 (没有包名)? [英] How can I compile classes in packages, to execute them later with "java Program" (without the package name)?

查看:142
本文介绍了如何在包中编译类,以便稍后使用“java Program”执行它们。 (没有包名)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的javac和包有一个快速的问题。

I have a quick question regarding javac and packages in Java.

我有一个简单的程序(我们称之为Program.java),目前在以下目录:

I have a simple program (we'll call it Program.java) which is currently in the following directory:


  • myRepository / myProgram

在myRepository / myProgram目录中的Program.java和其他.java文件中,我声明了包myProgram。* ,还包括 import myProgram。* ;

In Program.java and other .java files in the myRepository/myProgram directory, I have declared package myProgram.* and also included import myProgram.*;.

所以当我输入 javac myProgram / Program.java 时,它会编译很好,如果我输入 java myProgram / Program ,它运行正常。

So when I type javac myProgram/Program.java, it compiles fine and it runs fine if I type java myProgram/Program.

但是,我正试图获得.class文件将在 myRepository 目录中生成,而不是 myRepository / myProgram ,这是源文件所在的位置。我尝试了 javac myProgram / Program.java -d .. ,它在myRepository目录中生成了.class文件,但是当我尝试java Program时,它给了我以下错误:

However, I'm trying to get the .class files to be produced in the myRepository directory, not myRepository/myProgram, which is where the source files are. I tried javac myProgram/Program.java -d .. which produces the .class files in myRepository directory, but when I try "java Program", it gives me the following error:


线程main中的异常java.lang.NoClassDefFoundError:程序(错误的名称:myProgram / Program)。

Exception in thread "main" java.lang.NoClassDefFoundError: Program (wrong name: myProgram/Program).

有没有办法让.class文件显示在主目录(myRepository)中而不是源代码所在的位置(myRepository / myProgram)并且能够在myRepository中执行 java Program

Is there any way way I could get .class files to show up in the main directory (myRepository) instead of where the source codes are (myRepository/myProgram) and be able to execute java Program while inside myRepository?

推荐答案

最好将源代码放在目录source / myProgram上,并创建一个名为build的目录来放置.class文件。因此,你可以这样编译和运行:

You better put the source codes on the directory source/myProgram and create a directory called build to put the .class files. Thus, you can compile and run this way:

javac source/myProgram/Program.java -d build
cd build
java myProgram/Program

这篇关于如何在包中编译类,以便稍后使用“java Program”执行它们。 (没有包名)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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