How to compile java class (inside a package) without IDE - java

I'm working in windows 7, Java 7 and have following folder:
C:\..\myApplicationV
Inside this folder there are two folders with one java class each:
C:\..\myApplicationV\graphics\Circle.java
C:\..\myApplicationV\mains\UseCircle.java
Circle.java contains following code:
package graphics;
public class Circle {
public void describeCircle (){
System.out.println("A circle is round");
}
}
I've been able to compile Circle.java so therefore I have also following file:
C:\..\myApplicationV\graphics\Circle.class
UseCircle.java contains following code:
package mains;
import graphics.Circle;
class UseCircle{
public static void main (String[] args){
Circle circle = new Circle();
circle.describeCircle();
}
}
I try to compile this last one class, I place in:
C:\..\myApplicationV\mains\
and type:
javac UseCircle.java
but I'm getting following message:
UseCircle.java:3: error: package graphics does not exist
import graphics.Circle;
^
Doing some research I have found some information at:
http://docs.oracle.com/javase/tutorial/java/package/index.html
So I have solve this isuue by placing all java classes in one package and works fine. Also I have move UseCircle.java class to base folder:
C:\..\myApplicationV
And also works. The problem is when trying to use the two package. Do you know what could be wrong ?

Please specify the full package path while compiling
cd C:\..\myApplicationV\
javac mains/UseCircle.java
java mains/UseCircle

Open the command prompt in myApplicationV folder & do the following:
javac graphics\Circle.java
javac mains\UseCircle.java
java mains.UseCircle

Related

How to run a java program in command line?

Here is the thing: I am trying to run the example program in the joda-time project.
The start of the Examples.java file looks like this:
package org.joda.example.time;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Instant;
/**
* Example code demonstrating how to use Joda-Time.
*
* #author Stephen Colebourne
*/
public class Examples {
public static void main(String[] args) throws Exception {
try {
new Examples().run();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
And all the classes for compiling this Example.java is in a joda-time-2.3.jar.
I can successfully compile this program by using
javac -cp somewhere/joda-time-2.3.jar Example.java
And it generate an Example.class, but I jut cannot execute that.
So far I have tried:
java Examples
java -cp somewhere/joda-time-2.3.jar Examples
java -cp somewhere/joda-time-2.3.jar org.joda.example.time.Examples
But they all generate this kind of errors:
Error: Could not find or load main class org.joda.example.time.Example
Error: Could not find or load main class Examples
And I've tried both in the org/joda/example/time folder and the parent folder of org
Anyone can give an instruction on how to execute that? Really appreciate it!
Error: Could not find or load main class org.joda.example.time.Example
public class Examples {
Name of your class is Examples not Example
EDIT
Sorry for late reply...
To execute specific Java program you need to bring control to root directory so if your class is in abc/newdir/Examples.java you need to use cd command (in windows) to lead control to root directory and than compile or you can defeneitly go for the suggestion of kogut.
C:/abc/newdir>java -cp somewhere/joda-time-2.3.jar Examples
Modify your classpath parameter, so it should include directory where Example.class was generated.
In case of out/org/joda/example/time/Example.class you need to use
java -cp somewhere/jodata-time-2.3.jar:out org.joda.example.time.Example

Packages and Classpath

I have created a package in the following way, and stored the Simple1.java file in d:\p\javas
Simple1.java
package mypack;
public class Simple1
{
public static void display()
{
System.out.println("Welcome to package");
}
}
i compiled it using -d switch:
d:\p\javas> javac -d d:\p\notes Simple1.java
and i got the mypack package under the P\Notes folder in D Drive.
I want to set a permanent classpath for this package so that i can access it from anywhere in my system, and i tried doing so using the environment variables.
Now, when i try importing this package in another file which is stored at another location in my system, using:
import mypack.*;
and try accessing the Simple1.class file, i get error.
the code for new java file is:
packDemo.java
import mypack.*;
class packDemo
{
public static void main(String arg[])
{
Simple1 s= new Simple1();
s.display();
}
}
Could you please help me resolving the issue, and kindly let me know the exact way of setting the classpath also.
I want to set permanent classpath for both the locations i am using to store my .java files.
1.Simple1.class file is stored in below directory upto this is fine
d:\p\notes
2.set the classpath in environment variable as follows
variable:ClASSPATH
value:d:\p\notes
3.Now navigate to packDemo.java folder compile the packDemo.java using below switch
javac packDemo.java
4.run the .class file
java packDemo
This will work fine without any problems

Opening class in package from console in Java

So when i try to open a java class that's not in a package from the command prompt it all works fine, but when I try to open a class that's in a package it gives me NoClassDefFoundError.
And when I list the package when I try to open the class (java somepackage/someclass) it says that it can't load or find the main class.
Any help?
What I can infer is, you have two classes:
Test.java:
// no package defined here
class Test{
public static void main(String[] args){
System.out.println("Test");
}
}
so you can compile and run it using:
javac Test.java
java Test
Another class:
Test.java:
package test; // package defined here
class Test{
public static void main(String[] args){
System.out.println("Test");
}
}
And thus doing same thing gives you error.
For this you need to be in the parent directory of 'test' folder in your terminal or cmd and use:
java test.Test
No problem with compiler. You can compile as usual using javac Test.java from inside 'test' folder.
NoClassDefFoundError means that your JVM can't find your class at runtime. This could be because it's not visible (set to private or protected, or just no access modifier).
It could also be missing from your build path
package pkg1;
public class Dataguise{
public static void main(String [] args){
System.out.println("My name is Maninder Singh");
}
}
Suppose this is my code. My package name is pkg1.
1. First you need to create pkg1 dirrectory if not existed.
2. Run "javac Dataguise.java" command
3. It will generate the "Dataguise.class" file and move this file to "pkg1" folder
4. Now run "pkg1.Dataguise" command it will work.
I was having the same issue so sharing my experience.
What I assume is, you are creating a package and a class inside it, for example.
package com.vishwa.hello.commandLineArgs;
public class ComandLineArguments {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < args.length; i++) {
System.out.println("Command line arg is "+args[i]);
}
}
}
When I try to compile and run the above code in command prompt (from the package folder) as
javac ComandLineArguments.java.
java ComandLineArguments 123 456.
You get the below error:
Error: Could not find or load main class ComandLineArguments
Caused by: java.lang.NoClassDefFoundError: com/vishwa/hello/commandLineArgs/ComandLineArguments (wrong name: ComandLineArguments)
There are 2 ways to solve this:
Go to the root path of your project and then run.
java com/vishwa/hello/commandLineArgs/ComandLineArguments 123 456
789.
Command line arg is 123.
Command line arg is 456.
Command line arg is 789.
If you want to run the program from the package directory, you need to specify the class path along with the complete package
reference.
java -cp
/Users/16399/Documents/workspace-spring-tool-suite-4-4.12.1.RELEASE/CoreJava/src/
com/vishwa/ hello/commandLineArgs/ComandLineArguments 123 456 789.
Command line arg is 123. Command line arg is 456. Command line arg is 789.

Cannot run my own Java Package

I want to learn to write my own packages so I'm not also relient on an IDE, which I feel I have became. The problem is I cannot figure out how to run my own package, or what the proper method is to run your own package.
Here's a resource I used to learn some basics: http://javaworkshop.sourceforge.net/chapter3.html
Here's my current file structure:
Main.java
/src
projectaqua/
GameFrame.java
/classes
projectaqua/
GameFrame.class
I ran the command in the root directory of the project:javac -d ./classes/ ./src/projectaqua/*.java
I originally created a Main file in the /src/projectaqua directory and attempted to run the file. I was given this error:
Main.java:1: error: package projectaqua does not exist
import projectaqua.GameFrame;
I tried running the application in the /classes/projectaqua directory when compiling the Main file with the package, which gave me a class not defined error.
This compiled my package, the problem I'm facing is I don't understand how you are supposed to import your own package to run it, and where would the file to run the package be?
From what I've learned in school, when writing a GUI application we create a class that has a main function in it to instantiate the frame, and that's it's only job. Where would this be in this structure?
Intuitively it seems that file would be outside of the src files, but I feel like that removes the purpose of the src files. I haven't found anything useful on stackoverflow to this topic, if you do or have please point me in that direction.
More source code:
GameFrame Class:
package projectaqua;
import javax.swing.JFrame;
public class GameFrame extends JFrame
{
private int WINDOW_HEIGHT = 500;
private int WINDOW_WIDTH = 500;
private String title = "Project Aqua";
private boolean isVisible = true;
public GameFrame()
{
// Basic Window Defaults
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setTitle(this.title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Content Pane junk
// Will be added
setVisible(this.isVisible);
}
}
The Main class
import projectaqua.GameFrame;
public class Main
{
public static void main(String[] args)
{
GameFrame launch = new GameFrame();
}
}
I now see your problem.
In your question you were not clear that you had trouble running v. compiling. Had you posted this error trace it would have been immediately clear to me what your problem is:
unrollme-dev-dan:projectaqua Dan$ java Main
Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: projectaqua/Main)
Also note that had you Googled NoClassDefFoundError would have found this. The moral here is: understand and research your exact error.
Anyway
unrollme-dev-dan:classes java projectaqua/Main
is what you want. Notice the change of directory. I never bothered to understand why, has to do with relationship between package hierarchy and file structure hierarchy.
Java had two choices when designed: Assume the thing you are talking about is in the global package (yuck!) or try to guess what package it is in. It treats any folder below your working directory as packages. So even though it found a Main class in the directory from which you were running it did not find a Main class in the namespace corresponding to the directory . i.e. the global one.
When you run from one directory up and tell it to run something in projectaqua/ it is now looking for classes starting with projectaqua.
Alternately if you run
unrollme-dev-dan:projectaqua java projectaqua.Main
It looks for the right thing.
try this command at the root of your project
javac -cp ./classes -d ./classes ./src/projectaqua/*.java
Also make sure both your Main.java and GameFrame.java has package projectaqua; at the beginning

Java Command Line Trouble with Reading a Class from a Jar Archive

I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance
Here's a concrete example of what does work, so you can compare your own situation.
Take this code and put it anywhere, in a file called MainClass.java. (I've assumed a directory called src later. Normally you'd arrange the source to match the package, of course.)
package archiveFolder;
public class MainClass
{
public static void main(String[] args)
{
System.out.println("I'm MainClass");
}
}
Then run each of these commands:
# Compile the source
javac -d . src/MainClass.java
# Build the jar file
jar cf archive.jar archiveFolder
# Remove the unpackaged binary, to prove it's not being used
rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows
# Execute the class
java -cp archive.jar achiveFolder.MainClass
The result:
I'm MainClass
How are you building your jar file? Is the code in the appropriate package?
Does theMainClassName class have the following package line at the top:
package archiveFolder
You need the class file to be in the same directory structure as the declared package. So if you had something like:
org/jc/tests/TestClass.class
its source file would have to look like this:
package org.jc.tests;
public class TestClass {
public static void main(String[] args) {
System.out.printf("This is a test class!\n");
}
}
Then you could use the following to create the jar file and run it from the command line (assuming the current directory is at the top level, just above org):
$ jar -cf testJar.jar org/jc/tests/*.class
$ java -cp testJar.jar org.jc.tests.TestClass
Perhaps with java -jar archive.jar?
Of course, it supposes the manifest points to the right class...
You should give the exact message you got, it might shed more light.
EDIT: See Working with Manifest Files: The Basics for information on setting the application entry point (Main class) in your jar manifest file.
Usually this happens when a dependent class (static member) is not found - like this, using log4j:
public class MyClass {
private static Logger log = Logger.getLogger("com.example");
}
The reason is that the initialization of such a static member can be understood as part of the class loading - errors causing the class not to be available (loadable), resulting in the error you described.
Static constructors are another possible reason:
public class MyClass {
static {
// <b>any</b> error caused here will cause the class to
// not be loaded. Demonstrating with stupid typecast.
Object o = new String();
Integer i = (Integer) o;
}
}
I think others have covered some common stuff here. I'd jar tf the jar and make sure the class is listed. I'd also double-check that the class is public and the method is "public static void main(String[] arg)".

Categories

Resources