Java 将源文件编译到不同的目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18431857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:34:53  来源:igfitidea点击:

Compile source file to a different directory?

javadirectory-structure

提问by Jonathan Lam

Is there a way to compile a Java source file (*.java) to a different directory?

有没有办法将 Java 源文件 ( *.java)编译到不同的目录?

If my package file structure is like so:

如果我的包文件结构是这样的:

Mathematics ->
  Formulas ->
    src ->
      // source files containing mathematical formulas...
    bin ->
      // class files containing mathematical formulas...
  Problems ->
    src ->
      // source files containing mathematical problems...
    bin ->
      // class files containing mathematical problems...

I want to separate source and class files to keep the folders organized, but I currently have to copy all the class files from the srcfolders to the binfolders after every compile.

我想将源文件和类文件分开以保持文件夹井井有条,但我目前必须在每次编译后将所有类文件从src文件夹复制到bin文件夹中。

Is there a way to simplify this process by compiling the class files to another folder in the javaccommand?

有没有办法通过将类文件编译到javac命令中的另一个文件夹来简化这个过程?

采纳答案by Jon Skeet

Yup, absolutely - use the -doption to specify the output directory:

是的,绝对 - 使用-d选项指定输出目录:

javac -d bin src/foo/bar/*.java

Note that the directory you specify is the rootof the output structure; the relevant subdirectories will be created automatically to correspond to the package structure of your code.

请注意,您指定的目录是输出结构的;相关的子目录将自动创建以对应于您的代码的包结构。

See the javac documentationfor more details.

有关更多详细信息,请参阅javac 文档

In this case you'd need to issue one javaccommand to compile the formulae, and another to compile the problems though - potentially using the formulae bindirectory as part of the classpath when compiling the problems.

在这种情况下,您需要发出一个javac命令来编译公式,而另一个命令来编译问题 - 在编译问题时可能使用公式bin目录作为类路径的一部分。

(You might want to consider using a single source structure but different packages, mind you. You should also consider using an IDE to hide some of this complexity from you - it ends up getting tiresome doing all of this by hand, even though it's not actually hard.)

(您可能需要考虑使用单一源代码结构但使用不同的包,请注意。您还应该考虑使用 IDE 来向您隐藏一些这种复杂性 - 手工完成所有这些最终会变得很烦人,即使它不是其实很难。)