Unable to run classes with a package declaration - java

For some reason, I can't run ANY programs that begin with a package declaration.
Let's say I am trying to run a simple program called 'HelloDate.java'.
package Test;
import java.util.*;
public class HelloDate {
public static void main(String [] args) {
System.out.println("Hello, it's: ");
System.out.println(new Date());
}
}
Both HelloDate.java and HelloDate.class are located in the same folder:
/Users/eduarddedu/Desktop/Test
I am trying to run HelloDate from inside the 'Test' folder; 'pwd' returns:
/Users/eduarddedu/Desktop/Test
The CLASSPATH variable is not set to anything: echo $CLASSPATH returns an empty line.
To my mind, I should now be able to run the program with the command:
java HelloDate
But all I get is this: Error: Could not find or load main class HelloDate
I have also tried setting the CLASSPATH to (alternatively) :
/Users/eduarddedu/Desktop
/Users/eduarddedu/Desktop/Test
Still nothing works.
If I delete the package declaration at the begining, I can run the program just fine, from inside the 'Test' folder or from anywhere else, by setting the CLASSPATH variable.

You are running the file from the wrong directory.
Go to /Users/eduarddedu/Desktop and run:
javac Test/HelloDate.java
java Test.HelloDate

You should call java Test.HelloDate from outside the Test folder.

Related

Run single junit test with cli

I need to run a single test case run through the cli. I created a runner class
public class Runner {
public static void main(String ... args) throws ClassNotFoundException {
String[] classAndMethod = args[0].split("#");
Request request = Request.method(Class.forName(classAndMethod[0]),
classAndMethod[1]);
Result result = new JUnitCore().run(request);
System.exit(result.wasSuccessful() ? 0 : 1);
}
}
using this answer
Run single test from a JUnit class using command-line.
I downloaded from github a project (https://github.com/apache/incubator-dubbo) on which I want to run the single method, I positioned myself from terminal on the directory containing the Runner class I created and I launched the following command:
java -cp /path/incubator-dubbo/dubbo-cluster /usr/share/java/junit4-4.12.jar /pathClassRunner/src/com/company/Runner org.apache.dubbo.rpc.cluster.StickyTest#testHeartbeat
but I got the following error:
Error: Could not find or load main class pathClassRunner.src.com.company.Runner
can someone help me?
thanks
The command expects you to include any paths in the classpath with NO spaces. A space means that the arguments for the classpath has ended. It there is a space in one of your paths you may include double quotes:
java -cp path1:path2:path3 classname argument
java -cp "path1:path2:path3" classname argument
If a path starts with / it's a full path. If not it's relative to where you run your command. The classname must be the name of the class, not the file, so that means no .class. If your class specifies any package, then the classname is required to contain the package name too, and the path is to the root of the package, not the class itself.
Check that your user has proper access to the files, then try:
java -cp /path/incubator-dubbo/dubbo-cluster:/usr/share/java/junit4-4.12.jar:/pathClassRunner/src/com/company Runner org.apache.dubbo.rpc.cluster.StickyTest#testHeartbeat
I'm assuming your Runner is in the default package. In case it's in the com.company package, you'll want to run this instead:
java -cp /path/incubator-dubbo/dubbo-cluster:/usr/share/java/junit4-4.12.jar:/pathClassRunner/src com.company.Runner org.apache.dubbo.rpc.cluster.StickyTest#testHeartbeat
Another assumption is that your Runner.class is in your /pathClassRunner/src... directory.

Cant find or load main class

When I try to run a java program in the cmd it displays the messege "Could not find or load main class".
The problem occurs when there is a package involved in the program, otherwise it works fine.
The code is:
package myPackage;
public class index {
public static void main(String [] args){
System.out.println("Hello World");
}
}
I've tried writting in cmd: javac (name of package) . Class name, but still doesnt work.
The issue was that the class path needs to be set for each command (javac and java):
Attempted Steps
Compile index.java from the top_level. do not use sub package.
$javac -cp . importpackage/subpackage/index.java

Java Package Execution

Here's my Situation:
I have a folder Structure:
C:\Users\user\Desktop\JavaTraining\Chapter3\examples.
examples is also a folder. Now, I have a file name Calculator.Java in Chapter3 folder with the package statement package Chapter3;. So, from the Command Line I compiled the file from the JavaTraining directory as javac Chapter3\Calculator.java, It compiled and I see a file Calculator.class generated. But when I run the command java Chapter3.Calculator from the JavaTraining Directory. It throwed me an error: Could not find file or load main class Chapter3.Calculator.
Then, I created a sub folder in Chapter3 named examples and copied the Calculator.java into the examples folder and tried compiling and executing the file thinking Chapter3 as the root folder ( executed commands from the Chapter3 directory). No error, the file got executed.
Please can anyone explain me why this happened or what is the reason behind it, I am going mad...
Calculator.java is just a class Calculator with main function trying to find a sum from a printsum function of two variables.
I went through the suggestions provided in http://stackoverflow.com/questions/18093928/what-does-could-not-find-or-load-main-class-mean
According to the above, it was either the syntax mistake ( the way of trying to executing the file) or setting the PATH and CLASSPATH environment variables.
I even tried the echo %CLASSPATH% to see if my CLASSPATH variable is set to current directory. It did show me the . when I executed the echo command from JavaTraining directory.
The file did not execute when I tried Chapter3 folder as root directory, but when I create a subfolder in Chapter3 and made Chapter3 as the root directory, it executed, what might be the reason or what am I doing wrong,
Here is the command line with the output:
C:\Users\vikas\Desktop\JavaTraining>javac Chapter3\Calculator.java
C:\Users\vikas\Desktop\JavaTraining>java Chapter3.Calculator
Error: Could not find or load main class Chapter3.Calculator
C:\Users\vikas\Desktop\JavaTraining>cd Chapter3
C:\Users\vikas\Desktop\JavaTraining\Chapter3>javac examples\Calculator.java
C:\Users\vikas\Desktop\JavaTraining\Chapter3>java examples.Calculator
The sum is 30
C:\Users\vikas\Desktop\JavaTraining\Chapter3>
The Calculator.java file:
// One Package Statement
package chapter3;
// The file in Chapter 3 folder, file in example folder has
//package examples;
// One or more import statements
import java.io.*;
import java.util.*;
// Class Declaration
public class Calculator {
// State. Variables and Constants
int i=10;
long k = 20;
// Behavior, one or more methods
void printSum(){
long sum;
sum = i+ k;
System.out.println("The sum is " + (i+k));
}
public static void main (String[] args) {
Calculator c = new Calculator();
c.printSum();
}
}
When you build a file, it is good to have a build directory, then java will put the class in the correct package layout.
mkdir build
javac -d build path/to/source/Files.java
java -cp build package.name.Files

Error running Java on Sublime Text [OSX]

So I've tried to start compiling and running java on sublime, and it works fine if the package is not defined.
this compile and run:
public class Tester
{
public static void main(String[] args)
{
System.out.println("this is a test.");
}
}
But if I add a package:
package test;
public class Tester
{
public static void main(String[] args)
{
System.out.println("this is a test.");
}
}
I got this error
Error: Could not find or load main class Tester
[Finished in 6.8s with exit code 1]
[cmd: ['javac "Tester.java" && java "Tester"']]
[dir: /Users/ph/Documents/JAVA/test]
[path: /usr/bin:/bin:/usr/sbin:/sbin]
Any idea why is this happening or how to fix it?
[cmd: ['javac "Tester.java" && java "Tester"']]
[dir: /Users/ph/Documents/JAVA/test]
Sublime Text is trying to compile your program in a directory called "test" (see #2), which is the package name. It is looking for a file named "Tester.java" within that directory (see #1), but it doesn't exist because "Tester.java" is inside the current directory ("JAVA").
When compiling Java files in packages, the files need to be in a directory structure that reflects the package hierarchy. So you need to move your file to the directory that corresponds to the package it is contained in. For example, class "A" in package example.utils.letters would have to exist at the path ../example/utils/letters/A.java
Create folder "JAVA/test" and move Tester.java into there, then run it.

Trouble in compiling the java code

I wrote the following piece of code in sublime text on my macbook pro.
I saved the file inside the java folder on my desktop. When I tried to compile the program and tried to execute it, I am getting the fallowing error message " Error: Could not find or load main class Animals ".
Could someone help me in compiling and running this program
package forest;
class Animals{
public static void main(String[] args)
{
Animals s = new Animals();
Sring[] s2 = s.getAllAnimals();
}
public String[] getAllAnimals()
{
String[] s1= {"Lion", "Elephant", "Tiger","Deer","Wolf","Dinosar"};
return s1;
}
}
Make your class Animal as public and rename the file to Animal.java
Your class is in a package called forest so you need to move Animals.java into a directory called forest.
You hava a typo on line 7: Sring[] s2 = should be String[] s2 =.
Compile from the parent directory of forest. Something like this should work
$ javac forest/Animals.java
Run from the parent dir:
$ java forest.Aminals
Your program will have no output when you run it.
Look on your code there is no sring type class in java so change it to String
Sring[] s2 = s.getAllAnimals();
change it to
String[] s2 = s.getAllAnimals();
Everything will be good
try this tutorial Java and the Mac OS X Terminal and Make your class public and also make sure that the file name that contains your source code and the name of your main class is same, your main class is the one that contains main method.
First of all you can name your java file with any name.
Say Sample.java. and let us consider this file is present in D:\work
Go to D:\work folder in cmd prompt.
Keep this in mind :
If you write package forest, then your class has to be public.
So write public class Animals{}
While compiling do this javac -d Sample.java
By doing this the compiler will create the folder "forest" and inside that it will create the Animals.class.
So now in D:\work we have Sample.java file and "forest" folder
Now in your command prompt DO NOT go inside the "forest" folder.
Stay in work folder. D:\work
And Run this command from D:\work java forest.Animals
Explantion::
The name of your class that contains Main method is not Animals. It is forest.Animals This is the fully qualified name of the class. This happened becasue you put a package to it.
So while runnning you must run with fully qualified name
java forest.Animals
The name of your class is not Sample.java. <-- This is just a text file name it anything the complier will not generate a class with name Sample.class because inside this file there is no such class, the class name is Animals. So Animals.class will be generated.
And javac -d Sample.java helps you create the folder structure automatically based on the package.
For example if your class was like this
package com.stackoverflow.samples
public class Animals{
}
And you do java -d Sample.java
The Compiler will create a folder com inside that another folder stackoverflow inside that another folder samples and inside that a file Animals.class
To run this you must run it from outside the the "com" folder with fully qualified name
java com.stackoverflow.samples.Animals

Categories