I'm using IntelliJ IDEA and JDK 8.
I have some compiled Java Classes, and I imported them as an external library, as the code I have uses methods inside those classes. However, I can't seem to make actually use those .class files.
Whenever I try to run this code:
public static int spendOnCokes(int sum, DrinksMachineA mach) {
int count = 0;
mach.insert(sum);
try {
while (mach.getBalance() >= mach.getPrice()) {
mach.pressCoke();
count++;
}
} catch (EmptyMachineException e) {
}
It gives me the following error:
Error:(21, 45) java: cannot access com.sanac.DrinksMachineA
bad class file: /homes/jmcv3/Documents/Java/ClassesArchive/com/sanac/DrinksMachineA.class
class file contains wrong class: DrinksMachineA
Please remove or make sure it appears in the correct subdirectory of the classpath.
I've searched around, and some people seemed to suggest that it had something to do with the folder hierarchy/package name. It looks fine to me though. I also tried switching to JDK 5 as that's what the .class file was compiled with, to no avail. (Also read that somewhere.)
Here's a screenshot outlining the directory structure:
All I want is to be able to use those compiled .class files with my code. Seems to be so simple, so I must be missing something really stupid. Any ideas?
The answer is simple: .class files aren't external libraries.
You can play with jar.exe Java tool to export "ClassesArchive" to a .jar file.
File name and public class name should he same. Its a name issue by my perspective.
Related
I currently don't have a working way to edit and run Java on my computer, so I'm trying to get Atom working with Java (I realize it's not a Java IDE and I'm not trying to make it one, I just want to be able to do some light Java work on my laptop). I've installed the script and instant-build packages for Atom and wrote the following test code in a file called "main.java' in my project folder:
class Main{
public static void main(String[] args) {
System.out.println("please");
}
}
When I try to run the code with cmd+i (I'm on a 2012 MacBook Pro) and get the following error message:Error: Could not find or load main class main.
I'd be happy to provide any further information; thanks for helping!
The huge problem of learning Java is that you need to launch the projects in a very strict way, and setting the classpath is always problematic. The solution lays in the following (pretty enigmatic) line of the "Script" documentation:
Project directory should be the source directory; subfolders imply packaging.
So, instead of opening a plain file, open the project (folder) with .java classes or define inside the file, the package to which your .java belong.
It's due to the fact that JDE needs to create a virtual target in form of .classess and single .java file definitely can't be launched as standalone file. I suppose that "Script" is not able to locate the source folder when you try to execute seperate .java file.
Before launching your .java files always "Add Project Folder..."
Please remember that it's not possible to have several folders opened if they don't belong to the same project. Such situation cause problems of locating the right classpath and in the end javac prompts the error.
You have to name your file with the first letter in upper case Main.java, since it must match the name of your class
I replicated the issue quite easily. If I created a new directory in Atom itself and then tried to run the code it didn't work as your error message came up for me as well. Error: Could not find or load main class main.
I used an existing directory and then created a file inside that folder in Atom and ran the same code it worked. I then copied and pasted that same file into the directory of my choice and it worked.
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
I know this question has been asked loads of times before, but I'm a rookie programmer and despite trying many of the solutions on this site I still can't fix this issue. I'll be really thankful if you can take the time to figure out what I've done wrong.
Operating system: Windows 8
Java version: 1.8.0 update 25
The command prompt I'm using is the one that comes with Windows. (I'm presuming there are other types so I'm just making it clearer.) The code's a really basic one.
package com.thefinshark.intro;
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome.");
}
}
So, first I changed the directory to C:\javawork, where Welcome.java is saved. I set the path to C:\Program Files\Java\jdk1.8.0_25\bin, then compiled the code. The compilation seemed fine, I found the Welcome.class file in the C:\javawork as well. The execution, however, kept returning "Could not find or load main class Welcome". I've tried C:\javawork>java Welcome and C:\javawork>java com.thefinshark.intro.Welcome, and loads of other variations. I've also changed the classpath to C:\ and C:\javawork but it still dosen't work. Someone answering a similar question suggested adding dt.jar and tools.jar to the classpath but no dice.
It'll be great if someone could help, and I'll be happy to help pass on the information to the others who have problems like this as well. (As I'm typing this I'm looking at a whole long list of similar questions.)
The directory structure must match the package name of your source file. So, if your class is in the package com.thefinshark.intro, then your source file must be in a directory com\thefinshark\intro.
So, for example, you should save your source file as C:\javawork\com\thefinshark\intro\Welcome.java, and then compile and run it from the directory C:\javawork:
C:\javawork> javac com\thefinshark\intro\Welcome.java
C:\javawork> java com.thefinshark.intro.Welcome
Note: The javac command expects a filename of the source file you are compiling (com\thefinshark\intro\Welcome.java), and the java command expects a fully-qualified class name (com.thefinshark.intro.Welcome).
See Lesson: Packages for more details on how to work with packages.
Ok, I'm stumped here. I'm using Matlab version 2013b with a Java RTE of 1.7.0_11 and I'm trying to run a simple piece of code to see if Matlab is able to read the .jar file and nothing seems to be working.
Here is the Java code, which is compiled to a .jar named JavaOCT.jar, which is placed in the Matlab working directory:
package VTK;
public class vtkVolumeView{
public int Test(){
return 10;
}
}
That is it, no other dependencies, nothing fancy. In Matlab, I try:
javaaddpath('\JavaOCT.jar'); %<-Directory and name are 100% correct
import VTK.*; %<-Package name from above
methodsview VTK.vtkVolumeView; %<-Can't find the class, argh!
Matlab kicks back that it can't find the class.
Things I've done to try and solve the problem:
Reverted to the exact same JDK as the Matlab RTE
Tried an older 1.6 JDK
Done lots of stack overflow research to try and solve it 1 2 3 4
Tried used javaclasspath and pointing to the compiled class instead
Read the Matlab documentation 5
Using clear -java after the javaaddpath
Any help would be appreciated, it is driving me nuts!
Update: Daniel R suggested just javaaddpath('JavaOCT.jar') which doesn't work either.
Final update: It finally works! I wasn't building the .jar properly. In IntelliJ, click on the project and hit F4. This brings up the Project Structure, then go to Artifacts and click the green + button and add DirectoryContent and then point to the out\production. Once this is done, as mentioned by others, it should show up in Matlab as an expandable .jar.
I don't know which operating system you are using, but the ./ seems invalid.
Try javaaddpath('JavaOCT.jar'); or javaaddpath(fullfile(pwd,'JavaOCT.jar'));.
What does exist(fullfile(pwd,'JavaOCT.jar')) return?
Some things to try:
Add the class file. When using a package, you need to add the class file in at the host of the package. For example, if your code is here:
\\full\path\to\code\VTK\vtkVolumeView.class
Then use:
javaaddpath('\\full\path\to\code')
I'm still suspicious of your *.jar path. You should usually use absolute paths when adding jar files. Try adding the results of which('JavaOCT.jar')
How did you make your jar file? Does it contain the appropriate directory structure implied by your package declaration?
I'll try to illustrate the problem as simple as I can.
I have a JAR file, which I extracted using Winrar. (The jar file contains an open source android library).
I want to modify this JAR file by adding a new class to the library.
So here are my steps:
First, I created a class using Eclipse and set the package name same as the android's library package name.
Second, I copied this java File to the folder of the other java files in the library.
Third, I tried to compile the JAVA file via the CMD using javac.
The path of the new java file and the other .JAVA and .CLASS files of the library is: C:\com\example\core\
The name of the new java file would be: "MyNewClass.java"
The command I run via the CMD is: javac C:\com\example\core\MyNewClass.java
But, during the compilation I get many errors saying: Cannot find symbols.
I've been looking up for a solution of this problem but couldn't figure how to solve it and make the new JAR File having another class that I created seperately.
What am I missing?
As per earlier comments:
Rather than trying to modify the JAR, you can get access to the full source code of the Universal Image Loader library by cloning the repository using git or hitting "Download ZIP" on the righthand side of the page you linked.
Once you have the source, import the library in your IDE. From there on you'll be able to build the whole thing from scratch, make any adjustments/modifications you like, etc.
Your classpath might be wrong or there might be some mistake in package name.
When a Java program is being compiled the compiler it creates a list of all the identifiers in use. If it can't find what an identifier refers to it cannot complete the compilation. This is what the cannot find symbol error message is saying, it doesn't have enough information to piece together what the Java code wants to execute.
Try:
javac -cp com/* C:\com\example\core\MyNewClass.java
That should make the compiler aware of all the other classes under com/...