java package does not exist and bad source file

前端 未结 2 1722
有刺的猬
有刺的猬 2020-12-06 23:43

So I made a folder called util and placed four classes along with program named unit10Assignment in it. I created a package util and typed \" package util; \" at the top of

2条回答
  •  误落风尘
    2020-12-07 00:34

    I'm going to make the assumption that you have your project set up like this:

    util/
        Employee.java
        unit10Assignment.java
    bin/
    

    (If it isn't, that's fine - so long as they're in some folder. bin/ should exist, though.)

    The way that packages work is that they're folders on the hard drive - the package you want to import requires that the folder and class you wish to import both exist in that specific folder. This is why packages are handy - you can have two classes named Employee and have them live in completely different locations.*

    Here's how you compile these into a package-like structure without the use of an IDE. Substitute $HOME for the full path of your Java class folder.

    javac -sourcepath $HOME/util -d $HOME/bin *.java
    

    And here's how you run your main class:

    java -cp $HOME/bin util.$MAIN_CLASS
    

    A breakdown of what these flags mean:

    • -sourcepath instructs javac to look in this specific directory for your source files.
    • -d specifies an output directory for your .class files.
    • -cp instructs java to add this folder to its classpath.

    *: Really, really large projects can often use the same name as other classes; if you wanted to use a specific one, you'd have to use the fully-qualified class name for it.

提交回复
热议问题