Error could not find or load main class - java

I want to run my class in terminal window:
D:\workEclipse2\JUnitTest\bin>java -classpath D:\JUnit\hamcrest-core-1.3.jar;D:\
JUnit\junit-4.12.jar tax.TaxCommandLineRunner
Code of my TaxCommandLineRunner class:
package tax;
import java.util.List;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TaxCommandLineRunner {
public static void main(String[] args) {
// TODO Auto-generated method stub
JUnitCore core = new JUnitCore();
Result result = core.run(AllTests.class);
if(result.wasSuccessful()){
System.out.println("All tax tests was successfull");
}else{
System.out.println("These tax tests was failure");
List<Failure> fails = result.getFailures();
fails.forEach(failure -> System.out.println(failure.getMessage()));
}
}
}
Compiled AllTests.class and TaxCommandLineRunner.class are located in D:\workEclipse2\JUnitTest\bin.
My jars file are located in D:\JUnit
I can't find what I'm doing wrong.

I input in terminal window:
D:\workEclipse2\JUnitTest\bin>java -classpath D:\JUnit\hamcrest-core-1.3.jar;D:\JUnit\junit-4.12.jar;. tax.TaxCommandLineRunner
I assume that point after semicolon means classpath of Windows, that is in first case I don't include my standart java\jre.

You must also add the actual directory to your classpath:
D:\workEclipse2\JUnitTest\bin>java -classpath .;D:\JUnit\hamcrest-core-1.3.jar;D:\
JUnit\junit-4.12.jar tax.TaxCommandLineRunner

Related

How can I solve that type of issue when I compile using `javac`: " error: cannot find symbol [...]"?

For starters, I have to say that I am using IntelliJ IDEA Community Edition 2020.3.1 and running java 15.0.1 2020-10-20, also when I run my program after enabling assertions and clicking on the run button, it works as expected. That being said here is my file structure:
Here is the code in my TestRunner.java file:
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public final class TestRunner {
private static final List<Class<?>> TESTS = List.of(CalculatorTest.class);
public static void main(String[] args) throws Exception {
List<String> passed = new ArrayList<>();
List<String> failed = new ArrayList<>();
for (Class<?> klass : TESTS) {
if(!UnitTest.class.isAssignableFrom(klass)){
throw new IllegalArgumentException("Class "+ klass + " must implement UnitTest");
}
for(Method method : klass.getDeclaredMethods()){
if(method.getAnnotation(Test.class) != null){
try{
UnitTest test = (UnitTest) klass.getConstructor().newInstance();
test.beforeEachTest();
method.invoke(test);
System.out.println(method.invoke(test));
test.afterEachTest();
passed.add(getTestName(klass, method));
}catch(Throwable throwable){
failed.add(getTestName(klass, method));
}
}
}
}
System.out.println("Passed tests: " + passed);
System.out.println("FAILED tests: " + failed);
}
private static String getTestName(Class<?> klass, Method method) {
return klass.getName() + "#" + method.getName();
}
}
Here are my issues:
When I compile my main class TestRunner.java using javac TestRunner.java, it fails to find those symbols CalculatorTest.class, UnitTest.class, Test.class, UnitTest. Here is the error message:
When I use javac *.java though, my files compile and my .class files are generated, here is a screenshot:
but when I try to run my file using java TestRunner it says: "Error could not find or load class TestRunner, here is a screenshot:
If anyone can help me solve those issues I'd would be very happy. So far, I have found no solutions when I googled about them. Thank you!
After reading many answers, I found that the solution was simple.
First compiling TestRunner.java:
javac -cp . TestRunner.java
Then running TestRunner (containing my main function):
java -cp . -ea TestRunner
It turns out I was missing on the dot "."!
Here is the final result:

Java program not working using the command line

Short story :
When I run my java application through the Intellij it's all working.
When I run it through the command line I have some issues.
Long story:
First, I have to say that I have a 'lib' folder inside my project with all the Jars I need and I added it as a Library to the project.
When I compile it from the command line I have to specify a '-cp' to the lib folder, otherwise it doesn't load the jars. Even though it looks good, when I run my java application, I get a 'Error: Could not find or load main class awsUpdater' error
My commands :
For compiling -
javac -cp "../../../../lib/*" awsUpdater.java
For executing -
java -cp "../../../../lib/*" awsUpdater
Here's my class (besides the methods)
package AWSUpdater;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class awsUpdater {
public static void main(String[] args) throws IOException {
String bucketName = "bucket";
String key = "ket";
//AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
AmazonS3 s3Client = new AmazonS3Client(DefaultAWSCredentialsProviderChain.getInstance());
System.out.println("Downloading an object");
S3Object s3object = s3Client.getObject(new GetObjectRequest(
bucketName, key));
//Get new version of android
String newAndroidVersion = getNewAndroidVersion();
//Download current versions.json
String currentJson = displayTextInputStream(s3object.getObjectContent());
//Edit versions.json with new android version
String editedJson = editJsonWithCurrentAndroidVersion(currentJson, newAndroidVersion);
//String editedJson = editJsonDummyCheck(currentJson);
//Create new file to upload to S3
createFileWithNewJson(editedJson);
//Upload new file to S3
updateVersion(bucketName, key, "versions.json");
}
Would appreciate any help with how to compile and execute my program through the command line. thanks !
you need to add package name
java -cp "../../../../lib/*" AWSUpdater.awsUpdater
I notice that the class awsUpdater is under the package AWSUpdater, so you can not use java -cp "../../../../lib/*" awsUpdater directly.
For Example:
I create a project like this:
|-test
|-AWSUpdater
|-awsUpdater.java
Detail of the awsUpdater.java:
public class awsUpdater {
public static void main(String[] args) {
System.out.println("hello");
}
}
then(now I'm in test/AWSUpdater):
javac awsUpdater.java
java awsUpdater
Everything goes well!
If I add the class to the package, like this:
package AWSUpdater;
public class awsUpdater {
public static void main(String[] args) {
System.out.println("hello");
}
}
then(now I'm in test/AWSUpdater):
javac awsUpdater.java
java awsUpdater
here, it will got the error which is same with yours.
Now, you can go to the package's root dir. (here is test), and then:
javac AWSUpdater/awsUpdater.java
java AWSUpdater/awsUpdater
Now, you will get the correct result.

Java package and directories

It may be a similar to this question : package does not exist error!
but I don't understand how to manage it.
I try to follow this lesson (in French sorry) https://openclassrooms.com/courses/les-tests-unitaires-en-java
and so I have the following tree :
Garage/test/XXXTest.java, Garage/main/impl/XXX.java, Garage/main/inter/XXX.java
In test I have this code (GPSTest.Java)
package test;
import static org.junit.Assert.*;
import org.junit.Test;
import main.impl.GPS;
public class GPSTest
{
#Test
public final void GPSTest() {
GPS gps = new GPS();
double prix = gps.getPrix();
assertTrue("Test prix GPS", prix == 113.5);
}
}
and in main/impl I have this one (GPS.java)
package main.impl;
import main.inter.Option;
public class GPS implements Option
{
public double getPrix()
{
return 113.5;
}
}
and in main/inter I have (Option.java)
package main.inter;
public interface Option
{
public double getPrix();
}
When I try to compile (I'm in Garage)
javac -cp "C:\Program Files (x86)\Java\junit-4.10.jar" test\GPSTest.java
I have this error
test\GPSTest.java:6: error: package main.impl does not exist
import main.impl.GPS;
Do I need to add Garage in the package name ? In the lesson (linked above) it's the same architecture and the same package name... But they use Eclipse, so maybe there are some differences (I use the command line)
EDIT
If I remove the test part it works :
test\TestGPS.java
package test;
/*import static org.junit.Assert.*;
import org.junit.Test;*/
import main.impl.GPS;
public class GPSTest
{
// #Test
public final void GPSTest() {
GPS gps = new GPS();
double prix = gps.getPrix();
//assertTrue("Test prix GPS", prix == 113.5);
System.out.println(prix);
}
}
With the following command doesn't give error... So I suppose the problem is with the classpath, but how can I fix it ?
javac test\GPSTest.java
Do I need to add Garage in the package name
No, but you need to be in the directory Garage when you compile, such that you are at the head of the following directory tree:
main
main/impl
main/impl/GPS.java
main/inter
main/inter/Option.java
test
test/GPSTest.java
The problem was with the clathpass. I had to add the current file to the path with .; before the rest of the path:
javac -cp .;"C:\Program Files (x86)\Java\junit-4.10.jar" test\GPSTest.java

Loading a class from an external jar

This is my first java program, so please excuse me if its too naive.
I have a 3rd party jar. I want to instantiate a class in the jar and be able to use its methods. Some details about the class in the jar:
Class File: rediff.inecom.catalog.product.CSVAPI
Constructor: CSVAPI()
Method: UpdateCSVAPI(key, csvpath)
Return: String
I have written the following program:
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.IOException;
class MyLoaderClass{
public void myLoaderFunction(){
File file = new File("vendorcatalogapi.jar");
try {
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("rediff.inecom.catalog.product.CSVAPI");
Object cls_object = cls.newInstance();
System.out.println(cls_object);
String output = cls_object.UpdateCSVAPI(12345,"myfile.csv");
System.out.println(output);
System.out.println("try");
}
catch (Exception e) {
System.out.println("catch");
e.printStackTrace();
}
}
public static void main(String args[]){
new MyLoaderClass().myLoaderFunction();
}
}
I am trying to compile it using:
javac -cp vendorcatalogapi.jar temp.java
But I am getting the following error:
temp.java:17: error: cannot find symbol
String output = cls_object.UpdateCSVAPI(12345,"myfile.csv");
^
symbol: method UpdateCSVAPI(int,String)
location: variable cls_object of type Object
1 error
Looks like the object is not correctly initialized. Please can someone help me with the correct way of doing it
If this is your first java program, then loading the class dynamically is probably overkill. Just use it normally and let the default class loader load it:
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.IOException;
import rediff.inecom.catalog.product.CSVAPI;
class MyFirstClass{
public void myFunction() {
CSVAPI cvsapi = new CSVAPI();
System.out.println(cvsapi);
String output = cvsapi.UpdateCSVAPI(12345,"myfile.csv");
System.out.println(output);
System.out.println("Success!");
}
public static void main(String args[]){
new MyFirstClass().myFunction();
}
}
Compile (note that the source code file name must match the class name):
javac -cp vendorcatalogapi.jar MyFirstClass.java
Run:
java -cp .:vendorcatalogapi.jar MyFirstClass (on Unix based)
java -cp .;vendorcatalogapi.jar MyFirstClass (on Windows)
You have to let the compiler know that cls_object is an instance of CSVAPI. If you don't, you can only use the object methods (toString, equals, etc.).
To do this, you can do the following:
rediff.inecom.catalog.product.CSVAPI cls_object = (rediff.inecom.catalog.product.CSVAPI) cls.newInstance();
Please, note that you need to have CSVAPI in your classpath!
Object class doesnt know the methods of rediff.inecom.catalog.product.CSVAPI class.
Class cls = cl.loadClass("rediff.inecom.catalog.product.CSVAPI");
Object cls_object = cls.newInstance();
So, explicit casting is required
rediff.inecom.catalog.product.CSVAPI object =
(rediff.inecom.catalog.product.CSVAPI) cls.newInstance();
will do the job.

not able to include package created by own in java

I have written a program that checks a data set and provides a result, i.e. if a climate condition is given for 1000 days as data set to the program it will find any deviation in the program and provide as result that major deviation.
package main;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import faster94.*;
import rules_agarwal.*;
import algo_apriori.*;
import context_apriori.*;
import itemsets.*;
public class MainTestAllAssociationRules {
public static void main(String [] arg){
ContextApriori context = new ContextApriori();
try {
context.loadFile(fileToPath("ds1.txt"));
}
catch(Exception e)
{
e.printStackTrace();
}
/*catch (IOException e) {
e.printStackTrace();
}*/
context.printContext();
double minsupp = 0.5;
AlgoApriori apriori = new AlgoApriori(context);
Itemsets patterns = apriori.runAlgorithm(minsupp);
patterns.printItemsets(context.size());
double minconf = 0.60;
AlgoAgrawalFaster94 algoAgrawal = new AlgoAgrawalFaster94(minconf);
RulesAgrawal rules = algoAgrawal.runAlgorithm(patterns);
rules.printRules(context.size());
}
public static String fileToPath(String filename) throws UnsupportedEncodingException{
URL url = MainTestAllAssociationRules.class.getResource(filename);
return java.net.URLDecoder.decode(url.getPath(),"UTF-8");
}
}
The above is the main program. There are seven files and I have created by own package, but when I run this program as a whole I cannot run it. It complains that a package is missing. i have ready provided all the seven files.
Can any one be able to run those files?
Directory tree has to reflect package tree.
So if you have a class in a package named main you class file must be in a directory named main under the working directory. So if you execute from bin/ your class must be in bin/main.
Hope this helps
Edit
The directory tre has to look like this.
bin/
-----faster94/
--------------Classes or Subpackage
-----rules_agarwal/
-------------------Classes or Subpackage
-----algo_apriori/
------------------Classes or Subpackage
-----context_apriori/
---------------------Classes or Subpackage
-----itemsets/
--------------Classes or Subpackage
-----main/
----------MainTestAllAssociationRules and other classes or subpackages
To run this use java main.MainTestAllAssociationRules in the root (bin/) directory

Categories