How to create a package for different files? - java

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.

Related

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

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.

Compiling multiple java files within a single file?

Trying to compile a multi file package. Needing to compile via: javac mainfile.java while also compiling all the other (about 4 other .java files) at the same time through the one file? I have tried using statements like extend and import package.* Any help would be appreciated.
I have used different compiling methods and arguments but trying to do it just by only inserting javac mainfile.java and java mainfile
Summary: Trying to compile multiple java files at once, through java compiling a single file.
My current code for the main file:
package mypackage;
import mypackage.*;
public class mainfile{
public static void main(String[] args) {
Myfile.main(args) //run main from other file
}
}
Edit: Sorry for the lack of information, when compiling, the compiler returns:
MainFile.java:15: error: cannot find symbol
Myfile.main(args);
^
symbol: variable Myfile
location: class mainfile
1 error
javac as a tool does not do what you want. But, that's why other tools exist.
What you're asking for boils down to 'I want a build system'. The vast majority of java projects use maven or gradle.
It would seem like this works fine:
javac -sourcepath src src/mainfile.java
but you'd be deceived. That will merely compile all source files that are directly referenced by the code in mainfile.java, but there are many other ways to refer to code, such as SPI, reflection, XML config files. The vast majority of java projects will end up using some construct that ends up 'breaking' the -sourcepath "trick" sooner rather than later, which is presumably why all java projects use a build system instead of relying on -sourcepath.
Note that all source files act as if they have:
import java.lang.*;
import yourownpackage.*;
at the top, whether you write this out or not. And, import is java-ese for 'alias'. import foo.bar.Baz; means: Whenever 'Baz' appears in this file as a type, assume I meant to write 'foo.bar.Baz', and that is all: import foo.bar.Baz does not run any code that is in the Baz class whatsoever. If you don't use Baz, then the class file produced doesn't mention Baz at all. This will also not cause javac to then compile your entire 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 code not compiling with 'javac' but compiles in Eclipse

I have just written a Java multi-threaded program in Eclipse. It compiled fine and works like a charm.
However, as this is coursework we are required to ensure that it compiles in the command line using 'javac' otherwise we score ZERO!
So, some classes compile others don't. The error I'm getting is the following ( they are all similar just with different class names, this is one example)
GateRunnable.java:7: cannot find symbol
symbol : class Station
location: class package.name.here.GateRunnable
public GateRunnable(Station st) {
^
Is this a javac issue? Any help appreciated.
Your compile -classpath and/or -sourcepath is incomplete. The compiler doesn't know where to find class Station. Here is a related question that describes how to set the classpath to include all the classes you want.
To solve the problem I was having, it was simply necessary to compile all classes by using the following command:
javac *.java
which compiles all java files in the directory.
have you compiled every .java file in your folder/packages? if not, then do so. Eclipse usually does that for you, but within the terminal it's you taking the responsibility of compiling every part of the code.

NoClassDefFoundError and Could not find or load main class

I am using the code from Rome's tutorials page http://wiki.java.net/twiki/bin/view/Javawsxml/Rome05TutorialFeedReader . Also trying this one: http://wiki.java.net/twiki/bin/view/Javawsxml/Rome05TutorialFeedReader
Compiling works, but I'm not sure how to run these examples. Why I just type java FeedReader or java FeedAggregator into the command line, I get the error:
C:\projects\freshmeat\src>java FeedAggregator http://freecode.com/?format=atom
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/syndication/f
eed/synd/SyndFeed
plus the large block that follows this error
Why is this happening, how do I fix it and try these things out? How do I get something to work with Rome!?
You need to include rome in the runtime classpath (in addition to the compile-time classpath)
java -classpath lib/rome.jar FeedAggregator ...
The samples you are trying to run are in the package com.sun.syndication.samples. You say you are a complete beginner, so, to make things simpler, I would recommend that you remove the line beginning with package in each of FeedReader.java and FeedAggregator.java. Recompile the classes after removing their package directives.
Then, to run these classes, make sure you're in the same directory as the class files FeedReader.class and FeedAggregator.class that javac created. Then, try running:
java -cp c:\projects\freshmeat\libs\rome-1.0.jar;c:\projects\freshmeat\libs\jdom-1.0.jar;. FeedReader
(and similarly for FeedAggregator.)
Note also that I've added the current directory, ., to the -cp attribute. Without this, the Java virtual machine won't know that it has to look in the current directory to find your FeedReader and FeedAggregator classes.
If you were to reinstate the package directives, you'd find the class files FeedReader.class and FeedAggregator.class would be created inside a directory com\sun\syndication\samples when you compile their sources. To run the class files from this location, you'd use a command line such as
java -cp c:\projects\freshmeat\libs\rome-1.0.jar;c:\projects\freshmeat\libs\jdom-1.0.jar;. com.sun.syndication.samples.FeedReader
and you'd run this from the directory containing the com subdirectory, not the directory that contains the class files.
More information on packages in Java can be found here.

Categories