While creating one folder in src directory in one project in eclipse, it makes that folder a package. Is there any way to avoid this folder from automatically being a package?
e.g., I add main folder in src directory. I don't want it to become a package. How can I do this?
Suppose I add folders in this manner: src/main/org/apache. I don't want main.org.apache to be a package, instead, I want the packaging to start from org. (i.e., org.apache).
Eclipse forces you distinguish between source directories and ordinary folders. Any subdirectories in a source folder will be considered a package.
In your case, you can create an ordinary folder outside of src/ to prevent the subdirectories from being interpreted as packages.
Alternatively, you can modify the project properties to have src/ be considered an ordinary directory, and put a source directory within it.
You can manage which directories in a project are considered source directories by:
Right-clicking your project, then click Properties.
In the left pane, click Java Build Path. In the right pane, select the Source tab.
Here you can add/edit/remove source folders.
You need to go to Project -> Properties -> Java Build Path -> Source (tab).
Remove src from "Source Folders on Build Path"
Then add src/main as a source folder. If you already have org under main, then your packages should start with org as desired.
I added the "Excluded" pattern with value ** to 'Java Build Path -> Source - > src/main/resources' and my package became a simple folder in Eclipse.
When you run a Java project in eclipse, the current working directory is the root folder of the project. So why not just create your resource folder there?
ProjectDirectory
../bin
../src
../resourceDirectory
Then, in your project, you can fetch resourceDirectory with
public File getDirectory(String dir) {
File cwdir = new File(".").getParentFile(); // remove the "." in path
for (File f : cwdir.listFiles()) {
if (f.isDirectory() && f.getName().equals(dir)) {
return f;
}
}
return null;
}
and
File resourceDir = getDirectory("resourceDirectory");
if (null == resourceDir) {
System.err.println("Resource directory not found");
System.exit(-1);
}
Note : you might perhaps want to create an utility class for the getDirectory() method, or something similar. This is just an example.
Bottom line is that the application will most likely be launched where it should be and you might just use a startup file (.bat, .sh, etc.) to do that anyway. There is no need of putting resource directories inside your source or binary folder; keep them separated.
Any folder in src directory becomes a package. If you wish to have a main folder then create a source folder of name main and then create the required package in main folder.
Related
I have a Java Project in NetBeans 7.0.
I want to add some image to some label dynamically. The image will differ depending on the state of the program.
I put one such image, 'filling.jpg', in the 'resources' folder of my project.
I want to reach this file correctly (not by absolute or relative path, because that will cause problems when I build the jar file).
So I found this method:
ImageIcon fillingIcon = new ImageIcon(getClass().getClassLoader().getResource("filling.jpg"));
labelFontFilling.setIcon(fillingIcon);
It keeps give me java.lang.NullPointerException.
But I am sure that there is that image, because I can assign the image to the label from the NetBeans Properties menu for that label (but I don't want this, I want to add the image by Java code).
What am I doing wrong, and how can I get that image correctly?
This was a pain, using netBeans IDE 7.2.
You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
Add a resource folder to the src folder:
(project)
src
project package folder (contains .java files)
resources (whatever name you want)
images (optional subfolders)
After the clean/build this structure is propogated into the Build folder:
(project)
build
classes
project package folder (contains generated .class files)
resources (your resources)
images (your optional subfolders)
To access the resources:
dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));
and:
if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {
worked for me. Note that in one case there is a leading "/" and in the other there isn't.
So the root of the path to the resources is the "classes" folder within the build folder.
Double click on the executable jar file in the dist folder. The path to the resources still works.
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Project Folder
build
dist
lib
nbproject
resources
src
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image.
In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
For me it worked like I had images in icons folder under src and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
I have a project that reads graphics and sound effects from a folder labeled res. This folder is at the same directory level as the src folder. I have res marked as Resources Root.
I configured my artifact to include res as a Content Directory by way of
Project Structure -> Artifacts -> Add (Alt + Insert) -> JAR
Then, in the output layout tab, I pressed the Add dropdown box -> Directory Content -> res
When I run the project in Intellij, it finds the resources just fine. Here is a code snippet showing how I access the resources:
public static final Sfx VOID_SOUND = new Sfx(TinySound.loadSound(new File("res/audio/sfx/void_sound.wav")));
However, when I build the standalone artifact, then run the jar, it looks for the resource by prepending the parent directory of my machine to the file path, all the way to root. Here is how the terminal output looks:
/home/user/Demo/res/audio/sfx/void_sound.wav (No such file or directory)
Error getting resource stream!
Is there a way to configure the artifact build to where it looks in the proper place? I want the resources included inside the jar file so it acts as a standalone jar with no external dependencies.
I'm not familiar with Linux so please take this with a grain of salt. But to me, it looks like its trying to access the file from where it doesn't have permission. Have you tried moving the file or directory to a shared location where any user can access it?
All the files from resource/source folders inside your module's Content root are included into artifact on artifact build. You can explore the artifact content produced (the artifact is placed into a directory specified in Output directory field in Artifct's Generat Settings) yourself.
Make sure you are specifying the correct directory for the file. E.g. if the res folder is marked as the module's resource root the file path name in the artifact will start from the sub-folder inside the res directory, that is audio/sfx/void_sound.wav.
Now I understand why it doesn't work. It's because resources included within the JAR artifact must be included in the classpath and are accessible using getResource(). Resources outside the classpath must be accessed using a filepath. If you use a relative path, it will resolve to where the pwd where the JAR is launched form, not to inside the JAR, hence the reason it resolves back to root. The solution is to put the resources in the classpath and access them using getClass().getResource() or getClass().getLoader().getResource().
I have a runnable jar file which is not able to access my resources which reside outside of the default src directory. Based on my understanding from What is the difference between Class.getResource() and ClassLoader.getResource(), I should be able to access root/res/img/img1.png (see folder setup below) by using the following getResourceFile function:
public class Foo {
private static final ClassLoader CLASS_LOADER = Foo.class.getClassLoader();
public static File getResourceFile(String relativePath) {
// Since I'm using getClassLoader, the path will resolve starting from
// the root of the classpath and it'll take an absolute resource name
// usage: getResourceFile("img/img1.png")
// result: Exception in thread "main" java.lang.NullPointerException
return new File(CLASS_LOADER.getResource(relativePath).getFile());
}
}
folder setup:
root/
src/
foo/
bar/
res/
img/
img1.png
audio/
audio1.wav
The problem arises when I try to execute the jar executable itself. However, the strange thing is that I was not able to replicate this through eclipse IDE which was actually able to resolve the path correctly. I have added the resource directory to the build path via (Project -> Properties -> Java Build Path -> Add Folder) so Java should be able to find the resource folder at runtime.
Is there something I'm missing in terms of generating the jar file? When unpacking the jar file everything seems to be in order with the img and audio directories being in the root (given the above initial folder setup):
foo/
/bar
img/
img1.png
audio/
audio1.wav
Files can only be used to represent actual files in your filesystem. And once you package your files into a JAR, the resource (img/img1.png) is not a file anymore, but an entry in the JAR file. As long as you use the folder structure from within Eclipse, the resources are individual files so everything is fine.
Try this:
System.out.println(CLASS_LOADER.getResource(relativePath));
It will print a URL, but it will not be a valid path to a file in your file system, but to an entry within the JAR file.
Usually, you will only want to read a resource. In that case, use getResourceAsStream() to open an InputStream.
I am using IntelliJ IDEA 14 and I want to add file outside of src to the JAR file. This is my current project structure.
I want to add layout.txt and saveddata.txt to the JAR file executable. I've been googling on that for a while can't find the solution
In case you need to see my code. This is how I am reading file
private Path layoutPath = Paths.get("resources/layout.txt");
content = new String(Files.readAllBytes(layoutPath));
Here is my project structure
Create a folder called "resources" at the same level as "src"
Right click the folder, select "Mark Directory As -> Resources Root"
Make new directory with name as "resources" under your project root directory.
Right click on that directory and select "Mark Directory As" ==>"Resources Root" option.
It's still for me. I tried:
+ "Mark Directory As" ==>"Resources Root"
+ getClassLoader().getResourceAsStream()
+ getClass().getClassLoader().getResource()
and Thread.currentThread().getContextClassLoader().getResourceAsStream()
For me, the resources directory was already marked as Resources Root but the content was missing in the jar. I had to manually add the resources dir to the jar artifact using the Project Structure window.
Open Project Structures window
Select Artifacts and click on the + button and then select Directory Content
Choose resources directory
Press Apply then OK
Currently, in my eclipse project, I have a file that I write to. However, I have exported my project to a JAR file and writing to that directory no longer works. I know I need to treat this file as a classpath resource, but how do I do this with a BufferedWriter?
You shouldn't have to treat it as a classpath resource to write to a file. You would only have to do that if the file was in your JAR file, but you don't want to write to a file contained within your JAR file do you?
You should still be able to create and write to a file but it will probably be relative to the working directory - the directory you execute your JAR file from (unless you use an absolute path). In eclipse, configure the working directory from within the run configuration dialog.
You're probably working in Linux. Because, in Linux, when you start your application from a JAR, the working directory is set to your home folder (/home/yourname/). When you start it from Eclipse, the working directory is set to the project folder.
To make sure you really know the files you are using are located in the project folder, or the folder where your JAR is in, you can use this piece of code to know where the JAR is located, then use the File(File parent, String name) constructor to create your files:
// Find out where the JAR is:
String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
path = path.substring(0, path.lastIndexOf('/')+1);
// Create the project-folder-file:
File root = new File(path);
And, from now on, you can create all your File's like this:
File myFile = new File(root, "config.xml");
Of course, root has to be in your scope.
Such resources (when altered) are best stored in a sub-directory of user.home. It is a reproducible path that the user should have write access to. You might use the package name of the main class as a basis for the sub-directory. E.G.
our.com.Main -> ${user.home}/our/com/