How to compile java code?

China☆狼群 提交于 2019-12-11 06:06:35

问题


I have a bunch of java files and I am running the following code in an attempt to compile them.

"\Program Files\Java\jdk1.6.0_16\bin\javac" Main.java

And I am being shown this error message

Main.java:3: package colourtiler.patternsdoes not exist 
import colourtiler.patterns.draw;

The code it isreferring to is located in the folder patters/PatternColour.java, how can I get it to include this file?

thanks


回答1:


You need to include its path in the javac/java's -cp or -classpath argument. E.g.

javac -cp .;c:/path/to/colourtiler/patterns/draw Main.java

where c:/path/to/colourtiler/patterns/draw points to the package root of the dependency classes. If you have more, then you need to separate it by semicolon. If there are spaces in path, you need to quote the individual path. Alternatively you can also package it in a JAR file (or use an already packed one) and put the full file path to the JAR file in the classpath.

If gathering and typing the classpath get bored, consider using a batch/shell file.

Good luck.




回答2:


Use the -classpath (aka -cp) or -sourcepath arguments to set base source locations. Use the -classpath argument to specify binary dependencies (jar files or base .class file directories). Use the -d argument to specify the output directory.

One thing to watch out for is that namespaces (packages) must match directory structures.

C:\temp>dir /B /S
C:\temp\bin
C:\temp\foo
C:\temp\src
C:\temp\src\foo
C:\temp\src\foo\Bar.java
C:\temp\src\foo\Baz.java

C:\temp>type src\foo\Bar.java
package foo;
public class Bar extends Baz {}

C:\temp>javac -cp .\src -d .\bin src\foo\Bar.java

C:\temp>dir /B /S
C:\temp\bin
C:\temp\foo
C:\temp\src
C:\temp\bin\foo
C:\temp\bin\foo\Bar.class
C:\temp\bin\foo\Baz.class
C:\temp\src\foo
C:\temp\src\foo\Bar.java
C:\temp\src\foo\Baz.java

A class file declaring package foo; must be in the directory foo. A class file declaring package foo.foo; must be in the directory foo\foo and so on.

See the documentation for javac. See here for more extensive classpath documentation.




回答3:


I would need to see a file listing to be sure but it sound like it should be in colourtiler/patterns.




回答4:


You first need to compile patters/PatternColour.java and then add the resultant classes' location to your classpath when compiling Main.java




回答5:


You will gain a lot of times by installing Eclipse and configure the folder which contains the classes as an Eclipse project (using the Import feature).

It will avoid you to pass as arguments the required JAR libraries, the output folder,...



来源:https://stackoverflow.com/questions/1674046/how-to-compile-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!