I have few java files. Main.java uses Picture class from Picture.java file. I want to know how to compile and run Main from command line ?
Here is Main.java:
package com.company;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Main {
static Picture pic = null; // Picture class ???
public static void main(String[] args) {
long t1, t2;
String name = "bears.jpg";
pic = new Picture(name);
t1 = System.nanoTime();
pic.new_img = meanFilter(pic.img);
t2 = System.nanoTime();
pic.writeImage();
calculateTime(t1, t2);
}
and Picture.java:
...
public class Picture {
public BufferedImage img;
public BufferedImage new_img;
...
Assuming both classes are in the same directory use :
javac Picture.java Main.java
This way the dependent class (Picture.java) is compiled first before your Main.java
To run it you will need to specify the entire package structure and run it from the src directory :
java com.company.Main
You need to specify the whole package.
Try running this:
javac com.company.Picture.java com.company.Main.java
Related
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.
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
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.
I know C++ at a decent level and I am trying to learn java. This will be a silly question but I cannot figure out how to import a .java file into another. I am at Eclipse IDE and in my project I have two files:
FileReader.java
Entry.java
I want to import the Entry.java in the other file but no matter what I do I get an error. Can you help me? Thx in advance.
FileReader.java :
import java.io.*;
class FileReader {
public static void main(String[] args) throws Exception {
System.out.println("Hello, World");
Entry a(10,"a title","a description");
a.print();
}
}
Entry.java:
public class Entry{
int ID;
String title;
String description;
public Entry(int id, String t,String d){
ID=id;
title=t;
description=d;
}
public void print(){
System.out.println("ID:"+ID);
System.out.println("Title:"+title);
System.out.println("Description:"+description);
}
}
At this state I get an error that Entry cannot be resolved as a variable. So I believe that it is related to the import.
Firstly
Entry a(10,"a title","a description");
should be
Entry a = new Entry (10,"a title","a description");
If Entry is in the same package then you will not need to import it.
If Entry is in a different package, say com.example then you will need to do
Either
import com.example.Entry;
or
import com.example.*;
The second import will import all classes in the com.example package - usually not such a good thing.
You need new Entry
The new keyword creates the new object
Entry a = new Entry(10,"a title","a description")
a.print();
An Entry object is created with the a reference with the above instantiation.
For the import part of your question, if two files are in the same package, no import is needed. If you Entry class was in a different package than your FileReader class, then you would need to import mypackage.Entry
Try
Entry a = new Entry(/*args*/);
And if you need to import the class, then use the absolute name (package+class) and put it after import above the class declaration
import com.example.you.Entry;
In Eclipse you can do Ctrl+Shift+O to resolve all imports.
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