java package does not exist and bad source file - java

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 each one of the classes code like this:
package util;
public class Employee
Then i wrote:
import util.*;
import javax.swing.JOptionPane;
public class unit10Assignment
On top of the program. However when I compile it, it tells me. Anyone know why? I tried playing around with it and it disappeared when I typed in import java.util*; instead but I'm not sure that what my teacher wanted as her example did not have the java in front.
It also says " bad source file" "package does not contain class Employee " However, everything compiled and ran perfectly before I typed in the package statement and I have not made any change to the code since then. If I removed the package statement from the employee class tho, the same message would appear but it would say another class does not exist.
Thanks for any help
Note: whether or not i put java.util or just util, this problem with the bad source still appears.
thanks for any help

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.

Make sure that:
the filename matches the class name (e.g. Employee.java for class Employee)
the files are inside the corresponding folder according to their package (i.e. util)
Are you using any IDE? If not, using one realy helps a lot with this kind of things.

Related

How to compile and run java programs ignoring package info?

I have a pile of .java files. They all have the same class name public MyClass. They all have a main method. They all may or may not have a package declaration at top, and I do not know ahead of time.
I am trying to write a script to compile and run these java programs. This is easy for the files without the package declaration... I just do some cp operations to setup, javac MyClass.java and java MyClass, then rm to teardown. However, the files with the package declaration require special attention. I have a few options that occur to me, including deleting the package lines, or attempting to read the package lines so that I know what the resulting directory structure should be. Both of these require me to go parsing through the .java files, which makes me sad.
Is there a way to compile and run these files without having to parse the .java files? Something like:
javac --ignore_package_structure MyClass.java
would be ideal, but a quick look at the javac man pages suggests that such a thing doesn't exist.
If we can assume that each student submits a single source file named HelloWorld.java, then we can use the "Launch Single-File Source-Code Programs" feature added by JEP 330 in Java 11:
java HelloWorld.java
We don't run javac first, we don't get a .class file (no cleanup needed), and any package declaration is handled automatically.
Remember, the students are still allowed to use many classes, they just all have to be submitted to you in a single source file.
The name of the class doesn't even matter. The first class in the source file is executed.
There isn't any easy way to do this. You could use regex though, and replace all imports with this simple java regex:
"package \w+;"g
Simply stated, you create a Java program to replace all the package names.
How to replace files: Find and replace words/lines in a file

Run a java class without package structure

There is a class a.b.c.Hello of which I would just get the Hello.class file delivered. I would like to run using something like:
java Hello
//or
java a.b.c.Hello
This leads me to a NoClassDefFoundError. Normally I'd have the a/b/c dirs with the class insdie and I'd add them to the -classpath option, but:
Is there a way of running a class in a package like this without having to put it inside a/b/c to match the package name?
All solutions I've found state the directory structure has to match the package naming, but I'd like to run the .class file directly from the folder where it is without recreating the folder structure
Is there a way of running a class in a package like this without having to put it inside a/b/c to match the package name?
Yes: By using a jar. Put the .class file in the jar (with the correct path), and then:
java -cp TheJarFile.jar a.b.c.Hello
This is, of course, very much like putting it in an a/b/c directory; it's just that the directory is in the jar, not the file system.
The packages do not just structure your classes (in folders), they also create a namespace. While the simple class name is Hello, the real class name is a.b.c.Hello.
That's because class names might repeat frequently (in different libs, f.e), but must be addressable on the other hand. For example: 'User', 'Logger', 'List', 'Date'.
Its not recommended, but you can put your class in the default package, too. Just remove the 'package ...' line.

bad class file using javac

Some background: I'm a student just learning Java, and usually the professor handles making sure our assignments have the right class path. However, the whole semester I've been plagued by the same problem, and I still don't understand what's going wrong.
As an example, I have two files, MyProgram.java located in the folder "MyProject" and MyProgramTest.java located in the folder "ClassProject", which also contains "MyProject". MyProgramTest creates a MyProgram object and lets you test its functionality.
MyProgramTest has the line import MyProject.MyProgram; The compiling instructions my instructor gives is to use javac MyProject/*.java while in "ClassProject" which works fine. Then, we are to use javac MyProgramTest.java in the same directory. However, the compiler claims:
import MyProject.MyProgram;
bad class file: .\MyProject\MyProgram.class
class file contains wrong class: MyProgram
Please remove or make sure it appears in the correct subdirectory of the classpath.
So I don't quite understand why this is happening. MyProgram is in the MyProject directory, and that directory is in the folder I'm in. Since the instructor uses this exact method to compile these programs, I keep getting screwed since mine never compile correctly. Any idea what I'm doing wrong, or how I can fix the file to compile this way without changing the structure of the directories?
Ensure this:
The MyProgram.java file should contain this line at the top of the file:
package MyProject;
Compile MyProgram.java from the ClassProject folder:
javac -d . MyProject/*.java
Then Compile MyProgramTest.java from the same folder:
javac MyProgramTest.java
This will create the class files correctly in the appropriate folder structure.
This should solve your problem.
Hope this helps!

Why does android studio does not recognize the "package net.simplifiedcoding.spacefighter;" code? [duplicate]

I'm a C++ developer - not a java developer, but have to get this code working...
I have 2 public classes that will be used by another product. I used the package directive in each of the java files.
package com.company.thing;
class MyClass ...
When I try to compile a test app that uses that I add
import com.company.thing.*;
The javac compiler fails with errors about com.company does not exist. (even if I compile it in the same directory as the class files I just made a package of)
I am sure I am doing something bone-headed and silly.
I've read the http://java.sun.com/docs/books/tutorial/java/package/usepkgs.html pages and tried to set up a directory structure like /com/company/thing etc, but either I have totally screwed it all up or am missing something else.
EDIT
thanks for the suggestions - I had tried the classpath previously. It does not help.
I tried compiling
javac -classpath <parent> client.java
and the result is:
package com.company does not exist
I have the code I want to import (the two java files) in \com\company\product. I compile those fine. (they contain MyClass) I even made a jar file for them. I copied the jar file up to the parent directory.
I then did (in the parent directory with the client java file)
javac -cp <jarfile> *.java
the result is:
cannot access MyClass
bad class file: MyClass.class(:MyClass.class)
class file contains wrong class: com.company.product.MyClass
Please remove or make sure it appears in the correct subdirectory of the classpath.
EDIT
I got the client code to compile and run if I used the fully qualified name for MyClass and compiled it in the parent directory. I am totally confused now.
compiled with no classpath set - just
javac *.java
in the parent directory - and it worked fine.
I can get a test app to compile, but that is not going to cut it when i have to integrate it into the production code. Still looking for help.
EDIT:
Finally - not sure why it didn't work before - but I cleaned up all the files all over the directory structure and now it works.
Thanks
Okay, just to clarify things that have already been posted.
You should have the directory com, containing the directory company, containing the directory example, containing the file MyClass.java.
From the folder containing com, run:
$ javac com\company\example\MyClass.java
Then:
$ java com.company.example.MyClass
Hello from MyClass!
These must both be done from the root of the source tree. Otherwise, javac and java won't be able to find any other packages (in fact, java wouldn't even be able to run MyClass).
A short example
I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:
package testpackage;
import testpackage2.MyClass;
public class TestPackageClass {
public static void main(String[] args) {
System.out.println("Hello from testpackage.TestPackageClass!");
System.out.println("Now accessing " + MyClass.NAME);
}
}
Inside testpackage2, I created MyClass.java containing the following code:
package testpackage2;
public class MyClass {
public static String NAME = "testpackage2.MyClass";
}
From the directory containing the two new folders, I ran:
C:\examples>javac testpackage\*.java
C:\examples>javac testpackage2\*.java
Then:
C:\examples>java testpackage.TestPackageClass
Hello from testpackage.TestPackageClass!
Now accessing testpackage2.MyClass
Does that make things any clearer?
Yes, this is a classpath issue. You need to tell the compiler and runtime that the directory where your .class files live is part of the CLASSPATH. The directory that you need to add is the parent of the "com" directory at the start of your package structure.
You do this using the -classpath argument for both javac.exe and java.exe.
Should also ask how the 3rd party classes you're using are packaged. If they're in a JAR, and I'd recommend that you have them in one, you add the .jar file to the classpath:
java -classpath .;company.jar foo.bar.baz.YourClass
Google for "Java classpath". It'll find links like this.
One more thing: "import" isn't loading classes. All it does it save you typing. When you include an import statement, you don't have to use the fully-resolved class name in your code - you can type "Foo" instead of "com.company.thing.Foo". That's all it's doing.
It sounds like you are on the right track with your directory structure. When you compile the dependent code, specify the -classpath argument of javac. Use the parent directory of the com directory, where com, in turn, contains company/thing/YourClass.class
So, when you do this:
javac -classpath <parent> client.java
The <parent> should be referring to the parent of com. If you are in com, it would be ../.
You got a bunch of good answers, so I'll just throw out a suggestion. If you are going to be working on this project for more than 2 days, download eclipse or netbeans and build your project in there.
If you are not normally a java programmer, then the help it will give you will be invaluable.
It's not worth the 1/2 hour download/install if you are only spending 2 hours on it.
Both have hotkeys/menu items to "Fix imports", with this you should never have to worry about imports again.
The standard Java classloader is a stickler for directory structure. Each entry in the classpath is a directory or jar file (or zip file, really), which it then searches for the given class file. For example, if your classpath is ".;my.jar", it will search for com.example.Foo in the following locations:
./com/example/
my.jar:/com/example/
That is, it will look in the subdirectory that has the 'modified name' of the package, where '.' is replaced with the file separator.
Also, it is noteworthy that you cannot nest .jar files.
Just add classpath entry ( I mean your parent directory location) under System Variables and User Variables menu ...
Follow : Right Click My Computer>Properties>Advanced>Environment Variables

Java error - bad source file: file does not contain class x . Please remove or make sure it appears

Recently started studying Java for an exam.
While learning packages, tried this and got an error message. What I did was
//Creating class A (Within package the package: com.test.helpers)
package com.test.helpers;
public class A {
public void sayHello(){
System.out.println("Hello World");
}
}
//And then the class App utilising the class A
import com.test.helpers.*;
public class App{
public static void main(String args[]){
A a = new A();
a.sayHello();
}
}
I had both of these files in a directory called 'JavaTest' (on Windows 7), and first compiled the A.java using the command javac -d . A.java
And then, while attempting to compile App.java, I got the following error message:
App.java:5: error: cannot access A
A a = new A();
^
bad source file: .\A.java
file does not contain class A
Please remove or make sure it appears in the correct subdirectory of the source path.
1 error
However, the problem seems to resolve in two ways,
Deleting the Source file A.java
Changing the import statement from import com.test.helpers.*; to import com.test.helpers.A in the file App.java.
I'd be highly grateful if you can explain what happens here. Or I might be making a goofy human mistake or a syntax error.
Here's the link to the source files
Hi the problem here is that the JVM confuses the class file due to the ambiguous class file name in both the directory (the JavaTest as well as the com.test.helpers directory).
when you do javac -d . A.java the compiler makes a class file in the directory com.test.helpers and now it confuses it with the sourcefile there in JavaTest
Deleting the Source file A.java
When you delete the source file A.java from JavaTest, JVM knows now that the class file in com.test.... is to be used, ambiguity goes away.
Changing the import statement from 'import com.test.helpers.*;' to 'import com.test.helpers.A' in the file, 'App.java'.
Here you are specifying which particular file to use in your class implementation that is you are telling the compiler to use the file A.java from com.test... and not from JavaTest package
Now, the solution for this ambiguity to not ever be a problem for you, you must import the specific files with import statement i.e. import com.test.helpers.A; or if you want to do import com.test.helpers.*; then you must specifically use com.test.helpers.A in place of A everywhere in your current class implementation to tell the compiler not to confuse it with the source at JavaTest
I know it's a lot late for this particular answer, but I wanted to share my views for the upcoming readers, if it could help them in any way, it would be great.
Thanks!
move the A.java under folder JavaTest to com/test/helpers. the error you are seeing is for the compiler complaining that A.java is in a folder that does not match its package declaration. Remember, you cannot access A from App without A being in a package.
from under src driectory run the following command to compile your classes
src> javac ./*.java ./com/test/helpers/*.java
then from under src folder
src>java App
that should run your program.
the file A.java should be in the path JavaTest\com\test\helpers\A.java
and don't forget to compile it like this:
javac -d . com\test\helpers\A.java
every thing is in right place, java does not ask to put your A.java file, in the helpers folder
the whole reason why your code ran with the A.java file removed and not otherwise is:
when your app.java (or the main java file which is importing other classes in it, -->) is in a default package then while importing the classes it gives priority to the same directory and not to the package directory(if there exist any file that has the same name as the class file -> and thats why it gives error bad source file A.java -> as it wanted A.class)
And because of that there is a rule in java : That never place a .java file (of the same name)in parallel to the packages
so to solve this problem you have to either remove the file, A.java
or rename it (to any other name that does not present in the package)
or you can use fully qualified import statement
I have the same problem finally,
I was solved.
//Use like this
import com.test.helpers.A;
If u have a more than class in com.test.helpers then u can use import com.test.helpers.*;
If you are not using an editor with auto-save, it might be helpful to check if the code you have written has actually been saved to the java file previously created
The bad source file error may be wrong if it is preceded by another error (below) which, in my case, provided guidance for how to fix the real problem. From my log file:
Error 1: a\g\GoodClass error:duplicate class: a.g.GoodClass //Not the problem
Error 2: a\b\BadClass error: cannot access GoodClass //The problem
bad source file: a\g\GoodClass //No, it's fine
file does not contain class x.y.GoodClass //How to fix it
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
Java reports the first line of Error 2 because BadClass is using a wildcarded import, either import x.*; or import x.y.*;.
THE FIX: remove the wildcarded import from BadClass and add only the specific imports you need from library x.y.

Categories

Resources