Third party JAR's in java - java

I included the 3rd party jar file in the java project but still this is showing compile time error.
I included the path of the jar file in add external jar's in java.
package com.aamir;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;//compile time error occurs here.
public class ReadCSV3 {
public static void main(String[] args)
{
CSVReader reader = null;
try
{
//Get the CSVReader instance with specifying the delimiter to be used
reader = new CSVReader(new FileReader("SampleCSVFile.csv"),',');
String [] nextLine;
//Read one line at a time
while ((nextLine = reader.readNext()) != null)
{
for(String token : nextLine)
{
//Print all tokens
System.out.println(token);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Your problem is that you are including the source only JAR file. That's the problem right there. You have the sources only (uncompiled source) JAR file and not the binary JAR (it must contain the .class files). You need opencsv-2.2.jar instead.
Here is a zip file of the binary JAR.

I included the path of the jar file in add external jar's in java.
You need to add it to the project.
You didn't mention exactly how to added the jar. Can you please post the screenshot of
Right click project --> Build Path --> Configure --> Libararis (3rd Tab ) --> Add External Jar
You should add the jar here. Please do so if not already done.

What development tools are you using? Are you compiling at the command line or in an IDE?
If at the command line, you need to include the third party JAR in the CLASSPATH - either as an environment variable or as an argument to javac.
If in an IDE such as Eclipse, you need to specify the add the JAR to the build path in the project.
Firstly, just for sanity's sake, double-check that the JAR is in the build path - that you have given it the right name and the right path - you should see it in the Referenced Libraries section of your Java project if you expand it in the Project View. Try removing it and adding it again.
Then, secondly, check that the class you are importing exists - that you have got the right package name and class name (it is case sensitive). You should be able to expand the JAR in Eclipse and see the packages and classes inside it.
Thirdly, if you are certain that everything is correct, try to use Eclipse's auto-import feature - delete your import line and press CTRL-SHIFT-O (for Organise Imports) and see if it imports the right class.
If it is not auto-importing, then it indicates that the class is not in the class path. Try steps 1 and 2 again.
Also, try cleaning Project --> Clean --> Clean all projects

Related

create jar file with xml file inside using maven [duplicate]

This question already has answers here:
Include xml files in maven project
(2 answers)
Closed 4 years ago.
So I've been trying to deploy a project as a jar and it needs to read a file this way:
private static final String DEFAULT_PATH = "org/some/thing/cool/necesaryFile.xml";
public void readSomeFile() {
InputStream is = null;
try {
ClassLoader classLoader = SomeOtherClass.class.getClassLoader();
is = classLoader.getResourceAsStream(DEFAULT_PATH);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
safeClose(is);
}
}
public static void safeClose(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've tested this inside Eclipse and it works fine! Debugging I saw the path and there was no problem at all!
When I deployed the jar with maven it showed no error, but when I try to run project A with the jar as a dependency, I get
java.lang.IllegalArgumentException: InputStream cannot be null
And checking the jar inside project A, I can't find the necesaryFile.xml that was there before deployed.
The path for the xml file was like this:
C:/coolUser/workspace/src/main/java/org/some/thing/cool/necesaryFile.xml
so it was inside cool package with some java class.
So my question is, is there a way to tell maven not to erase the file (if that's even what's happening) when deploying the jar? Moving the location of that xml file is not an option (or at least I hope not to do it)
The maven command :
mvn clean deploy -U -Dmaven.test.skip=true -DaltDeploymentRepository=coolRepo::default::${REPO_LOCATION}
Place your .xml file in src/main/resources not in src/main/java. The recommended way is to keep them in resources. If you still want to keep them along with java class, then you have to explicitly tell the plugin (which you are using in your pom to build jar) to inlude xml files.

Get directory path of maven plugin in its own Mojo

I am creating a custom maven plugin. In one of its Mojos, I am reading a Xpp3Dom object from XML file using following code piece:
File pluginsFile = new File(
"absolute-path-to-file/plugins.xml");
Xpp3Dom Xpp3DomObject = new Xpp3Dom("plugins");
try {
FileReader reader = new FileReader(pluginsFile);
Xpp3DomObject = Xpp3DomBuilder.build(reader);
reader.close();
} catch (Exception e) {
// TODO throw exception
}
The XML file from which I am reading (plugins.xml) is stored in src/main/resources of the maven plugin itself. My question is, how do I point to that XML file without explicitly stating the absolute path to that file?
To be clear: I want this file to be under the directory of my maven plugin. It cannot be outside the maven plugin as it is a necessary part of the maven plugin and should not be changed by other maven projects that consume this plugin.
I have searched for a variable/method in Maven Mojo that would give me the absolute location of the maven plugin itself. If I get that, then I can just give the location as value-of-that-variable/src/main/resources/plugins.xml. But I am unable to find such variable. I have also tried for a way to pass properties from Maven plugin POM to one of its Mojos so that I can pass project.build.directory, but cannot find a way.
To be clear: I want to access a file that is under the maven plugin directory, in one of its Mojos.
Any suggestions will help.
I think the easiest form to read some of the own plugin's resources files is through the getResourceAsStream() API, because sooner or later, your plugin will be delivered as a JAR, and then the src directory will dissapear and there will remain only classpath resources:
try (InputStream input=getClass().getClassLoader().getResourceAsStream("plugins.xml")){
try(Reader reader=new InputStreamReader(input));
{
Xpp3Dom Xpp3DomObject = Xpp3DomBuilder.build(input);
} catch (Exception e) {
...
}
}
Anyway, in this way there is a risk that some other JAR of the classpath should contain a plugins.xml file by chance. To avoid (or at least reduce) this risk, you should package it:
src\
main\
resources\
foo\
bar\
MyMojo.java
plugins.xml
... and in this case, you must read it through getClass().getResourceAsInputStream().

How to include plain files and folders into Eclipse product/plugin?

I have a plugin, which is using some plain text and binary files when running.
This is because plugin is using some third-party code, which works as in conventional application, i.e. taking data from within application directory.
When I was running plugin from within Eclipse, these data was just laying inside project directory in some folders.
To access this data I was using code like
public static final String CorePropertiesPath = "conf/core.xml";
public static URL CorePropertiesURL;
//...
Bundle bundle = Platform.getBundle(ID);
CorePropertiesURL = bundle.getEntry(CorePropertiesPath);
try {
CorePropertiesURL = FileLocator.resolve(CorePropertiesURL);
} catch (IOException e) {
e.printStackTrace();
}
I.e. to access data from file in "core/core.xml" in my project's directory, I was first converting it with getEntry() method and then with resolve() method.
This was working.
But when started to create products, I found that my files like "core/core.xml" just absent in target directory. Probably they should reside in my bundle jar, but they are not there.
How to force them to come in prescribed place?
Check build.properties file (you can edit it on the 'Build' tab of a manifest editor). Add
Eclipse-BundleShape: dir
in your MANIFEST.MF if you want to generate a directory and not a jar for your bundle.

I'm having trouble embedding HSQLDB into a simple Java (Eclipse) project

After reading up on some options (sqlite, derby etc...), I've decided to throw down with HSQLDB. I've downloaded it, read up on it and followed a 'hello world' type intro to it, and am now stuck.
I believe that you have to put the hsqldb.jar file in the src folder, so I did exactly that. Then I made a reference to the package with Eclipse by going into Run -> Run Configurations, then going into the Classpath tab, then clicking User Entries, then add External Jar, and selecting hsqldb.jar.
I get this :
java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
Here's my code :
package mysqlite;
import java.sql.*;
public class myclass {
public static void main(String[] args) {
try {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:db";
String user = "aUser";
String password = "";
Connection conn = DriverManager.getConnection(url, user, password);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
I understand it's unable to find a class, but I thought that was what the hsqldb.jar provided.
No, you do not have to put it into src folder. src is for source files (*.java). You have to add this jar into your classpath: click on project properties, choose "Java build path", select tab "Libraries" and add the jar here.
The jar can be stored anywhere in your file system. Sometimes people create lib directory under project home and put all 3rd party dependencies there.
Try putting the .jar here:
<YOUR_JAVA_HOME>\jre\lib\ext

Where to put a textfile I want to use in eclipse?

I need to read a text file when I start my program. I'm using eclipse and started a new java project. In my project folder I got the "src" folder and the standard "JRE System Library" + staedteliste.txt... I just don't know where to put the text file. I literally tried every folder I could think off....I cannot use a "hard coded" path because the text file needs to be included with my app...
I use the following code to read the file, but I get this error:
Error:java.io.FileNotFoundException:staedteliste.txt(No such file or directory)
public class Test {
ArrayList<String[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
URL url = Test.class.getClassLoader().getResource("src/mjb/staedteliste.txt");
System.out.println(url.getPath()); // I get a nullpointerexception here!
loadList();
}
public static void loadList() {
BufferedReader reader;
String zeile = null;
try {
reader = new BufferedReader(new FileReader("src/mjb/staedteliste.txt"));
zeile = reader.readLine();
ArrayList<String[]> values = new ArrayList<String[]>();
while (zeile != null) {
values.add(zeile.split(";"));
zeile = reader.readLine();
}
System.out.println(values.size());
System.out.println(zeile);
} catch (IOException e) {
System.err.println("Error :"+e);
}
}
}
Ask first yourself: Is your file an internal component of your application?
(That usually implies that it's packed inside your JAR, or WAR if it is a web-app; typically, it's some configuration file or static resource, read-only).
If the answer is yes, you don't want to specify an absolute path for the file. But you neither want to access it with a relative path (as your example), because Java assumes that path is relative to the "current directory". Usually the preferred way for this scenario is to load it relatively from the classpath.
Java provides you the classLoader.getResource() method for doing this. And Eclipse (in the normal setup) assumes src/ is to be in the root of your classpath, so that, after compiling, it copies everything to your output directory ( bin/ ), the java files in compiled form ( .class ), the rest as is.
So, for example, if you place your file in src/Files/myfile.txt, it will be copied at compile time to bin/Files/myfile.txt ; and, at runtime, bin/ will be in (the root of) your classpath. So, by calling getResource("/Files/myfile.txt") (in some of its variants) you will be able to read it.
Edited: Further, if your file is conceptually tied to a java class (eg, some com.example.MyClass has a MyClass.cfg associated configuration file), you can use the getResource() method from the class and use a (resource) relative path: MyClass.getResource("MyClass.cfg"). The file then will be searched in the classpath, but with the class package pre-appended. So that, in this scenario, you'll typically place your MyClass.cfg and MyClass.java files in the same directory.
One path to take is to
Add the file you're working with to the classpath
Use the resource loader to locate the file:
URL url = Test.class.getClassLoader().getResource("myfile.txt");
System.out.println(url.getPath());
...
Open it
Suppose you have a project called "TestProject" on Eclipse and your workspace folder is located at E:/eclipse/workspace. When you build an Eclipse project, your classpath is then e:/eclipse/workspace/TestProject. When you try to read "staedteliste.txt", you're trying to access the file at e:/eclipse/workspace/TestProject/staedteliste.txt.
If you want to have a separate folder for your project, then create the Files folder under TestProject and then access the file with (the relative path) /Files/staedteliste.txt. If you put the file under the src folder, then you have to access it using /src/staedteliste.txt. A Files folder inside the src folder would be /src/Files/staedteliste.txt
Instead of using the the relative path you can use the absolute one by adding e:/eclipse/workspace/ at the beginning, but using the relative path is better because you can move the project without worrying about refactoring as long as the project folder structure is the same.
Just create a folder Files under src and put your file there.
This will look like src/Files/myFile.txt
Note:
In your code you need to specify like this Files/myFile.txt
e.g.
getResource("Files/myFile.txt");
So when you build your project and run the .jar file this should be able to work.
Depending on your Java class package name, you're probably 4 or 5 levels down the directory structure.
If your Java class package is, for example, com.stackoverflow.project, then your class is located at src/com/stackoverflow/project.
You can either move up the directory structure with multiple ../, or you can move the text file to the same package as your class. It would be easier to move the text file.
MJB
Please try this
In eclipse "Right click" on the text file u wanna use,
see and copy the complete path stored in HDD like (if in UNIX "/home/sjaisawal/Space-11.4-template/provisioning/devenv/Test/src/testpath/testfile.txt")
put this complete path and try.
if it works then class-path issue else GOK :)
If this is a simple project, you should be able to drag the txt file right into the project folder. Specifically, the "project folder" would be the highest level folder. I tried to do this (for a homework project that I'm doing) by putting the txt file in the src folder, but that didn't work. But finally I figured out to put it in the project file.
A good tutorial for this is http://www.vogella.com/articles/JavaIO/article.html. I used this as an intro to i/o and it helped.
Take a look at this video
All what you have to do is to select your file (assuming it's same simple form of txt file), then drag it to the project in Eclipse and then drop it there. Choose Copy instead of Link as it's more flexible. That's it - I just tried that.
You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.

Categories

Resources