简体   繁体   中英

Java file layout without IDE (OS: Ubuntu)

I am writing some Java code without IDE, I got a little problem when I try run the code after compiling it. (I am using Ubuntu 64)

$ javac ClassName.java
$ java ClassName
Could not find or load main class ClassName

My directory structure is the following:

Projectname
----- PackageName
---------- className.java
---------- className.class

My code start by writing down the packageNmae. When I remove the package statement, it works. While error occur when that statement is included.

package PackageName;

public class myClass {
    // .... to be used in the main class
}

public class ClassName {
    public static void main(String args[]) {
        // ....
    }
}

Could anyone tell me what is the problem.

The main issue is where are you trying to run the command from. You do not run it from inside the package directory, but from the root of your package tree (in your example, the Projectname directory).

From there, you should be doing:

javac PackageName.className

which tells it to compile "className"[sic] inside package "PackageName"[sic]. The way you are doing it, you are telling it to compile a class that is not part of a package (which is strongly discouraged).

Notes:

  • Each file can only have a "general" class, with the name of that file.

You may define inner classes inside a class, but that would be inside the code block of the class.

package packageName;

public class ClassName { public class InnerClass { ... }

public static void main(String args[]) { ... } }

  • File name and class name must be the same. That includes case (lowercase or uppercase) of the name.

  • Class names always begin in uppercase.

  • Package names should be in camelCase .

  • Usually you do not want to leave your compiled (.class) files with the source (.java) files. The usual structure is, at the minimum:

 --> Project --> src --> myPackage --> MyClass.java --> bin --> myPackage --> MyClass.class

so you only need to copy your .class files to distribute the executable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM