Java program from command line fails. But Jar works fine [duplicate] - java

I have read the previously posted questions. Some are vague and none solved my problem so I am forced to ask again.
I have two simple classes,
package One;
import One.Inner.MyFrame;
public class test
{
public static void main(String args[])
{
MyFrame f= new MyFrame();
}
}
And the other class is,
package One.Inner;
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame
{
public MyFrame()
{
setPreferredSize(new Dimension(400,560));
setVisible(true);
}
}
I am at base folder "basic" in Windows cmd. I compile using
basic> javac *.java -d .
A folder and subfolder is created.
cd One
basic\One> java test
This generates a big set of errors. Many answers directed to specify the full path which didn't work.
My classes are in One so specifying One using -cp didn't work either.

You'd run it as:
java One.Test
... but from the root directory (basic), not from the One directory. You always specify the fully-qualified class name.
Oh, and package names in Java should be lower-case, so it should be one and one.inner, not One and One.Inner. Just a convention, but one which pretty much everyone follows.

If the directory is:
basic\One
Run java from the base directory of the package:
basic>java One.test or basic>One.test <optional arguments>
(ideally the package would be lowercase and the class upper case):
basic>java one.Test
If you get 'does not exist' messages, then the java command cannot find classes you referenced in your class. You can point to them with the -cp option ('.' means 'here', and you can add as many places as you like divided by ';' on Windows and ':' on Linux).
basic>java -cp . one.Test
or
basic>java -cp .;..\..\someJar.jar;c:\someDirectory\classesDirectory one.Test

The following line of Haralan Dobrev code solves the problem.
java -cp ../ one.Test

while creating a class with a package if you want to run it from cmd you must created a directory with same name of package put the .class in it and then you can easily run it for example you created a class with name "one" and this class in the package with name pack ,you must run these commands
1 javac one.java
after compilation created a directory with the name pack ,after that run this command
2 java pack.one
Note:
all this must be done in the current working directory and the name "one" i chose it here as file name and main class name
we all know the first name used in the first command is file name and second one is main class name

This is because if you are declaring package in your java file, then JAVA compiler believe you are having same folder architecture in your system.
In your case Java compiler looking for One as a package and then test.class., or to be very specific just look inside your .class file you can see what path it looking for. Please have a look for below Image (I my case I use Hello and Tester)
As you can see path in image is Hello/Tester(my case example), so architecture should be like Hello->Tester.
And if you are not having same architecture and want to create same while compiling, then use javacp command.

Related

Importing jar file to use like a library but having an error

First of all thank you for reading my question.
I have a .jar file and .java file which I should compile
They are "fractals.jar" and "FractalsTest.java"
So basically "fractals.jar" contains .class files with packages to run a simple program that displays fractals on a java program, and the directory looks like this.
fractals -- FractalExplorer
| FracalGenerator
| JImageDisplay
+ generator -- Mandelbrot
-- BurningShip
-- Tricorn
So, The top three classes are under directory(folder) and package called "fractals"
the the three fractal patterns under directory(folder_ and package named "fractals.generator"
FractalGenerator utilizes the three fractal pattern classes by importing them, and FractalExplorer class
is the class that contains the main function.
I have succeeded in compiling the six classes and compressed them as "fractals.jar" file with manifest including "Main-Class: fractals.FractalExplorer". Eventually, the "fractals.jar" file runs perfectly fine.
But my goal here is to make another java file that utilizes the "fractals.jar" file like a library to run the same thing!!!
So here is the code of "FractalsTest.java"
import fractals.*;
public class FractalsTest
{
public static void main(String[] args)
{
FractalExplorer fracExp = new FractalExplorer(800);
fracExp.createAndShowGUI();
fracExp.drawFractal();
}
}
I tried compiling it by entering on the cmd like this:
>javac -classpath fractals.jar FractalsTest.java
(assuming they both are on desktop)
It compiles perfectly fine, and "FractalsTest.class" is created.
And now all I need to do is entering
java -classpath fractals.jar FractalsTest
BUT!!!! The console screen shows that
"Could not find or load main class FractalsTest" with "java.lang.ClassNotFoundException: FractalsTest"
Please help!!!What mistakes have I done?????
I guess java -classpath fractals.jar FractalsTest searches for FractalsTest.class inside fractals.jar. Simple java FractalsTest should do the trick.
Edit: This answer states that the current directory must be manually added to the classpath. So add :. at the end of your classpath to include the current directory.

Using class files from a jar file that already has the path built

I'm a little lost here. We were given a jar file which contained 3 different .class files in it. I successfully built the path to the jar file, but I don't know how to use them. The class files obviously contain methods that can be used, but I've never worked with a jar file before so I don't know how to use them. I'm not sure if I have to import them somehow, how to instantiate them or anything. I have searched for tutorials to no avail.
All I'm looking for is some guidance so I can get moving on this project. If it is a case where I have to import them somehow how would I do it? For example, I have WikiEdits.class contained in WikiEdits.jar. The name of my main class is P2. Can someone show me a brief example of how this works?
Add the jar to your classpath, if you are using an IDE.
Then, a java class that uses it would look like something like this:
package p2;
import blah.WikiEdits; //references a class in the jar
public final class P2 { //(this is a strange name for a class, by the way)
public static void main(String... args){
//builds a new object of the given class
WikiEdits thing = new WikiEdits();
}
}
If you are using the command line, these examples may help:
http://www.javapractices.com/topic/TopicAction.do?Id=243
you need to add WikiEdits.jat to your path project, then import and instanciate the class.
import WikiEdits
P2 p = new P2();
p.somemethod();
Static class:
WikiEdit.someMethod();
In your java class add the relevant imports from the jar. And then from command line, you can compile and run your class using the classes from jar by definining the right classpath:
Compilation
on windows:
javac -cp .;pathtoyourjar YourClass.java
on linux:
javac -cp .:pathtoyourjar YourClass.java
Execution
on windows:
java -cp .;pathtoyourjar YourClass
on linux:
java -cp .:pathtoyourjar YourClass
If you are using Eclipse then follow this link to know the steps to add jar to your project:
http://www.cs.duke.edu/courses/cps004g/fall05/assign/final/addlibrary.html

Java classpath confusion

I wrote and tested a small Java program using Eclipse. I'm now trying to deploy it on a Windows 7 box and Java cannot find the class. I copied the class file to C:\dxtester\classes. I'm trying to run it from the dxtester directory with: C:\dxtester>java -classpath classes;. dxtester
This produces this exception which I think I understand. Java examined the class file and is prompting me to provide the fully qualified name.
Exception in thread "main" java.lang.NoClassDefFoundError: dxtester (wrong name:
dxtester/dxtester)
If I use the FQN I get
C:\dxtester>java -classpath classes;. dxtester.dxtester
Error: Could not find or load main class dxtester.dxtester
The application is a simple test driver where everything is done in main().
package dxtester;
public class dxtester {
public static void main(String[] args) {
This seemed like an extremely simple thing to do but I'm completely baffled. What am I missing?
Your current directory is dxtester;
in this directory you have dxtester.class (I presume);
your classpath is the current directory.
This setup is wrong: your classpath must be the base directory such that package names correspond to its subdirectories. In your case you should cd to C:\ and repeat the command; ideally, however, you will have your package structure in a dedicated directory instead of the root.
I should also mention that class names should be in CamelCase.

Exception in thread "main" java.lang.NoClassDefFoundError

package pack;
public class sample{
public static void main(String input[])
{
NumberFormat numberFormat = new DecimalFormat("#,##0.00##");
System.out.println(numberFormat.format(44533125.00));
}
}
the code is working fine in the current dir.. (c:/myprogram/).
after that i copy the sample.class file and paste it in other dir(d:/myprogram).
i got error while running, like
Exception in thread "main" java.lang.NoClassDefFoundError: sample (wrong name: pack/sample)
In java .class file can run anywhere right? but why i am not able to run?
You should have the class file within the package - so it should be in a directory called pack. Then with the parent directory in the classpath, you'd run
java pack.sample
(You should also change the class name to Sample to follow conventions, btw - and run pack.Sample.)
If you're building with javac, specify the "-d" option to tell it the base directory, and it will create the appropriate package structure if necessary. For example:
javac -d classes Sample.java
or
javac -d classes src/pack/Sample.java
will (in both cases) create
classes/pack/Sample.class
You could then run
java -cp classes pack.Sample
IntelliJ and maybe other IDE's do not refactor your Run/Debug configuration. You must manually change your package name preceding the name of your Main class. For instance, change 'sample.Main' to 'com.company.package.ui.Main' so it will launch correctly next time you try to run it.
The IDE might have already marked the Run/Debug button with a red cross because it couldn't find the main class. It also gives a warning when you open the Run/Debug configuration.
If you are not using a single java/class file you can also remove the package statement.

How to create a package for different files?

How do I create a Java package for different files? I have tried
the following. What have I done wrong? And what is the
right procedure?
The first file is:
package dil;
public class Hello
{
Support sp=new Support();
int i=sp.tin();
public void man()
{
System.out.println(i);
}
}
The second file is:
package dil;
class Support
{
public int tin()
{
return 3;
}
}
Now while I compile hello.java it shows these errors:
Hello:4:cannot find symbol
symbol: class Support
location: class dil.hello
Support sp=new Support();
^
Hello:4:cannot find symbol
symbol: class Support
location: class dil.hello
Support sp=new Support();
^
Where is the problem and how can I put both
these files in a package?
The files are in c:\src.
Assuming UNIX / Linux pathnames, a UNIX shell, etc, you need the following file structure:
/some/where/dil
/some/where/dil/hello.java
/some/where/dil/Support.java
Then set $CLASSPATH to /some/where, and compile using the commands
cd /some/where
javac dil/*.java
and run using
java dil.hello
Alternatively, you can tell java and javac what classpath to use with the -cp command line option.
You should also fix the following errors in the code:
Change the name of the "hello" class to "Hello", and rename the source file to match. Strictly speaking this is not an error, but it is a gross violation of the standard for naming Java classes.
You declare a member as "ten" but refer to it as "tin". Fix one or the other.
The entry point method in the "hello" class should be called "main" not "man", and should have a signature public static void main(String[] arg). If you don't fix these the code will compile, but the java command won't find the entry point and will fail.
Although the Support class is not public, that would not be a problem as both classes share the same package. My guess would be that you did not put both source files into a directory according to their packagename and call the javac compiler from the current directory where hello.java resides.
If a class is in package a.b this means the project structure should contain a folder ./a/b containing yourclass.java.
In your case, try to create a folder named ./dil, put your source files in it and call javac from its parent folder.
See Creating and Using Packages in Sun's Java Tutorials to learn all the details of using packages in Java.
I've spotted some things you have to check:
class hello starts with a lower case
class hello calls for sp.ten() instead of sp.tin()
Support isn't public. Make it public and try again.
I suggest you try using one of the free IDEs like Netbeans, Eclipse or IntelliJ CE. This will help you start coding rather than setting everything up the hard way.
BTW: These IDEs have quick fixes for most common problems so they not only give you the error but give you options to fix them and do it for you.

Categories