Java - Problem with the classpath on Eclipse - java

I'm trying to recompile a project I've been working on and I keep getting an error message when trying to load a property file:
The system cannot find the path specified.
I guess this has to do with the classpath. But I've added the path to the file in Properties-> Java build path-> Libraries (external class).
I also checked the .classpath file generated by eclipse, and the path is really there!
Why isn't Eclipse looking at the right path?

There 2 different classpaths, build classpath and runtime classpath. The one you are setting is the build classpath.
Check your runtime classpath by going to Run -> Run Configurations and select your application configuration. Check the classpath setting there.
There is another workaround for this also. Eclipse by default will include your output folder (usually named bin) in your classpath. Typically anything that are not compilable in src folder will be copied to bin as is. I assumed your property file is not located in src folder. What you can do is to open your project property and add the folder where your property is located into Java Buld Path -> Source (tab). This way eclipse will copy the content of that folder into bin and will be in the classpath.

There are several ways to read a property file:
Have it in the current working directory (the one cd'ed to). You can do this in the Eclipse launch configuration. (Run -> Run...)
Include it in your application, by having it in a source folder. You then need to read it in through a class loader to be able to get it always (when jarred up, through Java Web Start, etc).

Double check if the property file or its directory is in the excluded list of the project Source. If it is remove the exclusion filter and try recompiling.

Related

How to include resource folder in executable .jar file in eclipse?

I need to create an application for sorting various types of polygons using various parameters such as height, volume or base area. Arguments for Filename which has parameters for polygons, Sort type, Sort method will be pass through command line.That file is in my resource folder outside my src folder in a project. I have implemented all programs, It works fine when I run using pass arguments through eclipse run configuration. But when I try to run my .jar file using cmd same arguments it gives me FileNotFoundException.
I opened my jar file using 7zip and noticed it never extracted my resource folder in .jar file. I searched online and tried including my resource folder in to build path of eclipse. But still does't work.
Follow these steps:
1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder.
2) create your JAR!
EDIT: you can make sure your JAR contains folder by inspecting it using 7zip.
Reefer this link as well How do I add a resources folder to my Java project in Eclipse
First, you need to create a source folder for resources, for instance name it res, and then move your image folder to res. When you generate the jar file, you will see the image folder, not the res folder or files separately.
This comes down to how you are generating the JAR file.
When you're exporting the jar in eclipse make sure to checkbox the button that says "Export java sources and resources" https://www.cs.utexas.edu/~scottm/cs307/handouts/Eclipse%20Help/ensureJavaFiles.jpg
There are a lot of ways to do this one is to use Gradle is the recommended way, something like this will work Creating runnable JAR with Gradle

Can't Access resource path, only the target path

I want to access the resource's form of my project "\src\main\resources" but for any reason I can only access the target classes.
Here is my code:
System.out.println(Main.class.getResourceAsStream("/123.txt")); // java.io.BufferedInputStream#66cd51c3
System.out.println(Main.class.getResource("/123.txt")); // file:/C:/Users/Raul/workspace/Serial/target/classes/123.txt
System.out.println(Thread.currentThread().getContextClassLoader().getResource("123.txt").getPath()); // /C:/Users/Raul/workspace/Serial/target/classes/123.txt
and here my Project Dirs:
The thing is, even if I delete all the files in the target/classes and run the code, the compiler will copy the files from "src/main/ressources" into "target/classes" and read them from there.
I want to access the resource's form of my project "\src\main\resources" but for any reason i can only access the target classes.
I think the question is answered by user #VGR. Just to clarify it in another words:
You put your resources in the /src/main/resources folder, and these resouces will be copied as is into the /target/classes folder when you build your project.
Example
src/main/resouces/123.txt -> target/classes/123.txt
src/main/resources/myresources/145.txt -> target/classes/myresources/145.txt
...
Now if you run the program inside of your IDE you'll observe the following:
System.out.println(Main.class.getResource("/123.txt"));
output: file:/C:/Users/Raul/workspace/Serial/target/classes/123.txt
System.out.println(Main.class.getResource("/myresources/145.txt"));
output: file:/C:/Users/Raul/workspace/Serial/target/classes/myresources/145.txt
But if you open the generated jar file you'll not see the target folder because the file 123.txt will be on the root of the jar file and the file 145.txt will be under the folder myresources/145.txt.
The folder target is just an output directory for the build tool and will not be packaged within your jar file.
Now to the following question:
the problem is that i dont know how to export the target classes to my jar, or how can I get "src/main/ressources" as return value.
To answer this question you have to look into your pom.xml file on the root of your project. There should be a <packaging>jar</packaging> entry in it. If that is so you create the jar file as follows:
Option 1: from the command line
mvn clean install
the jar file will be created and copied into the folder target.
Option 2: from within Eclipse (for example)
right click on the pom.xml > Run AS > Maven install
the jar file should also be generated and copied into the folder target.
Note: on your screenshot there are two jar files: core-0.0.1-SNAPSHOT.jar and Serial-0.0.1-SNAPSHOT.jar; remove them (mvn clean or right click > Run AS > Maven clean) before generating the jar file. The reason is Maven can only generate one jar file per Maven module / project, afaik.
You are seeing the intended behavior. A Java program is compiled into an executable form—meaning, .class files and resources. When other users run your program, they will not have access to the source, so your code should not assume your source tree will be available.
Simply put, your code is correct as is. Do not attempt to read the source tree. If you want target/classes to contain up-to-date files, rebuild your project.
A word of caution: Never use the getPath() method of URL to convert a URL to a file name. There are many characters which are not permitted in URLs, and those characters will be “percent-escaped” in order to conform to the URL specification; as a result, the path portion of a URL is not a valid filename! The only correct way to convert a URL to a file is Paths.get(url.toURI()). However, you should not even try to convert a resource to a file at all, because once you move on to packaging your programs in .jar files, your resources will not exist as regular files at all, only as entries in .jar files (which are actually just zip files with some Java-specific entries added).

Classpath jar files in eclipse

I am new to eclipse and I have a general question about referencing external Jar files.
I went to the buildpath -> configure build path and added my two jar files that I wanted to reference as parts of an external library but I can seem to make an instance object of the classes in that jar.
And also I tried just copy and pasting the jar files to the extension folder of the standard library too but this also doesn't work.
How can I use the instance objects of the classes included in these jar files?
Even if you build path to external JARs you have to import the required classes because they do not actually exist inside the same package you are working at.
if u want to add external jars into eclipse follow these steps
Rightclick on project - Select Configure Build Path... and the project properties window will appear showing your build path configurations.
Click Add Variable --Click Configure Variables
Click New -Type a name for the new variable.--Browse to the directory that contains the JAR for the path.
Click Ok to define the variable.--Click Ok to close the preferences dialog.
Select the variable from the list.--Click Extend..
Select the JAR(s) that you want to add to the classpath.--Select the JAR(s) that you want to add to the classpath.-Click Ok to close the new classpath variable dialog.
If you already added jar file into classpath and if it doesn't work I would try below on command prompt
java -classpath example.jar;

How to resolve classes with source src-jar library in Eclipse?

I have added this jar file to my project's build path under "libraries":
http://sunet.dl.sourceforge.net/project/jeplite/jeplite/jeplite-0.8.7/jeplite-0.8.7a-src.jar
and cannot get Eclipse to resolve ANY of the included classes.
Packages are visible, but no classes.
Error message is:
"JEP cannot be resolved to a type"
In eclipse, it should be on the build path if its a source tree .... Remember , a jar is just a glorified zip file, so be sure that the binaries are actually in your jar file. The steps to test are
1) unzip the jar file
2) if its source : then either try adding it to your build path, or just directly import the source folders into your project
3) if you see class files in the jar, then it should be okay to add them to "libraries"
This is only a jar containing the source code. You need a jar with the compiled classes in it. Try the jeplite-0.8.7a-bin.jar.

Where is the correct location to put Log4j.properties in an Eclipse project?

Where in my Eclipse project should I add the log4j.properties file so that it will work as intended?
you can add it any where you want, when you run your project, configure the classpath and add the location of the log4j.properties files by clicking on:
Run->Run Configuration -> [classpath tab] -> click on user Entries -> Advanced -> Select Add Folder -> select the location of your log4j.properties file
and then -> OK -> run
and it should get loaded
The safest way IMO is to point at the file in your run/debug config
-Dlog4j.configuration=file:mylogging.properties
! Be aware: when using the eclipse launch configurations the specification of the file: protocol is mandatory.
In this way the logger will not catch any logging.properties that come before in the classpath nor the default one in the JDK.
Also, consider actually use the log4j.xml which has a richer expression syntax and will allow more things (log4j.xml tahe precedence over log4j.properties.
Add the log4j.properties file to the runtime class path of the project.
Some people add this to the root of the source tree (so that it gets copied to the root of the compiled classes).
Edit:
If your project is a maven project,
you can put the log4j.properties in the src/main/resources folder (and the src/test/resources for your unit tests).
If you have multiple environments (for example development and production),
want different logging for each environment,
and want to deploy the same jar (or war, or ear) file to each environment
(as in one build for all environments)
then store the log4j.properties file outside of the jar file and put it in the class path for each environment (configurable by environment).
Historically, I would include some known directory in each environment in the classpath and deploy environment specific stuff there.
For example,
~tomcat_user/localclasspath where ~tomcat_user is the home directory of the user that will be running the tomcat instance to which my war file will be deployed.
The best way is to create special source folder named resources and use it for all resource including log4j.properties. So, just put it there.
On the Java Resources folder that was automatically created by the Dynamic Web Project, right click and add a new Source Folder and name it 'resources'. Files here will then be exported to the war file to the classes directory
If you have a library and you want to append the log4j:
Create a folder named "resources" in your projet.
Create a .properties file named log4j
Set properties in log4j.properties file
Push right button in the project and go to properties->Java Build Path and, finally, go to the "Source" tab.
Push Add folder and search the "resources" folder created in step 1.
Finish.
(I have assumed that you have the log4j library added.)
PD: Sorry for my english.
This question is already answered here
The classpath never includes specific files. It includes directories and jar files. So, put that file in a directory that is in your classpath.
Log4j properties aren't (normally) used in developing apps (unless you're debugging Eclipse itself!). So what you really want to to build the executable Java app (Application, WAR, EAR or whatever) and include the Log4j properties in the runtime classpath.
Put log4j.properties in the runtime classpath.
This forum shows some posts about possible ways to do it.
I'm finding out that the location of the log4j.properties file depends on the type of Eclipse project.
Specifically, for an Eclipse Dynamic Web Project, most of the answers that involve adding the log4j.properties to the war file do not actually add the properties file in the correct location, especially for Tomcat/Apache.
Here is some of my research and my solution to the issue (again specifically for a Dynamic Web Project running on Tomcat/Apache 6.0)
Please refer to this article around how Tomcat will load classes. It's different than the normal class loader for Java. (https://www.mulesoft.com/tcat/tomcat-classpath) Note that it only looks in two places in the war file, WEB-INF/classes and WEB-INF/lib.
Note that with a Dynamic Web Project, it is not wise to store your .properties file in the build/../classes directory, as this directory is wiped whenever you clean-build your project.
Tomcat does not handle .property files in the WEB-INF/lib location.
You cannot store the log4j.properties file in the src directory, as Eclipse abstracts that directory away from your view.
The one way I have found to resolve this is to alter the build and add an additional directory that will eventually load into the WEB-INF/classes directory in the war file. Specifically....
(1) Right click your project in the project explorer, select 'New'->'Folder'. You can name the folder anything, but the standard in this case is 'resources'. The new folder should appear at the root level of your project.
(2) Move the log4j.properties file into this new folder.
(3) Right click the project again, and select 'Build-Path'->'Configure Build Path'. Select the 'Sources' tab. Click the 'Add Folder' button. Browse to find your new folder you created in step (1) above. Select 'OK'.
(4) Once back to the eclipse Project Explorer view, note that the folder has now moved to the 'Java Resources' area (ie it's no longer at the root due to eclipse presentation abstraction).
(5) Clean build your project.
(6) To validate that the .properties file now exists in WEB-INF/classes in your war file, export a war file to an easy location (right click Project -> Export -> War file) and checkout the contents. Note that the log4j.properties file now appears in the WEB-INF/classes.
(7) Promote your project to Tomcat/Apache and note that log4j now works.
Now that log4j works, start logging, solve world problems, take some time off, and enjoy a tasty adult beverage.
You do not want to have the log4j.properties packaged with your project deployable -- that is a bad idea, as other posters have mentioned.
Find the root Tomcat installation that Eclipse is pointing to when it runs your application, and add the log4j.properties file in the proper place there. For Tomcat 7, the right place is
${TOMCAT_HOME}/lib
In general I put it in a special folder "res" or "resources as already said, but after for the web application, I copy the log4j.properties with the ant task to the WEB-INF/classes directory. It is the same like letting the file at the root of the src/ folder but generally I prefer to see it in a dedicated folder.
With Maven, the usual place to put is in the folder src/main/resources as answered in this other post.
All resources there will go to your build in the root classpath (e.g. target/classes/)
If you want a powerful logger, you can have also a look to slf4j library which is a logger facade and can use the log4j implementation behind.
For a normal (non maven and non web) java project in eclipse.
Create a "source" folder with new options and with any name (as a standard we can name it as resources) under the project directory
push the log4j.properties file to this "source" folder.
Build and run the application.

Categories