eclipse create jar file with txt file that can be referred to - java

I have a project in eclipse
foo_project
- src
- bar_package
bam.java
info.txt
- info.txt
- resources
- info.txt
In bam.java, say, I print the content of info.txt out like
try {
welcome = new BufferedReader(new FileReader("src/info.txt"));
String currentLine = null;
while ( (currentLine = welcome.readLine()) != null) {
System.out.println(currentLine);
}
welcome.close();
} catch (Exception fof) {
System.err.println(fof.toString());
}
It is working inside eclipse as it is when I put info.txt under src folder, however, it doesn't work once I export this project to a JAR file.
In the code, I tried just "info.txt" as well as "src/info.txt", none of them is working! As you can see, I put info.txt pretty much everywhere and not successful!
How can I refer to this info.txt in the Java code, and make Java find it at both inside eclipse and JAR file?

If the text in your info.txt will always be the same, instead of treating the text as a file, consider treating it as a "resource". If you do that , you can include it within your JAR, instead of having to distribute it as a separate file.
You open an InputStream to a resource using the Class.getResourceAsStream() method.

I think to load files from Jar file the file reader method will not work effectively, you will have to use class.getResource() or class.getResourceAsStream() methods
some helpful links,
Load a resource contained in a jar
How to load resource from jar file packaged in a war file?
Load resource from class's own JAR file
Also as others have suggested make sure the Jar file contains the txt file you looking for, you can either use "jar" command or winRAR

To access resources inside a JAR file, you need to use
YourClass.getClassLoader().getResourceAsStream("info.txt")
This way it will look inside the JAR file (or rather, in all places on the classpath) for the file as a Resource. It will work in both Eclipse and when packaged as a JAR.

I ended up using in the class
getClass().getResourceAsStream( "/info.txt") which gives an InputStream
Then I use InputStreamReader and BufferedReader to read out the file.
/ here is the src folder. Everything under this folder will be built to bin folder at the end.
If you have multiple source folders (a folder can be set to be source folder by right click and choose that option in Eclipse), all source folders built to single bin folder
For example,
if you have source folders
sourceA
foo_package/...
sourceB
bar_package/...
then in bin, it will be
bin (this is the "/")
foo_package/...
bar_package/...
Thanks for all the answers and inspiration to all!

you must put your txt file next to the jar file in your jar folder
it means that copy your txt file into your jar file folder not into jar file

Related

File only accessible when placed in a location where it will be erased from the jar

I'm new to NetBeans IDE, and am struggling with accessing a file after building the jar file. After reading through many posts on this topic, I decided to try the following code:
BufferedReader read = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/file.txt")));
This works fine when my file is placed inside the "build" folder of the project where the .class files are, but of course this is a problem because it is erased in the "clean and build" process when the jar file is created. I have tried placing it in the src folder, in a separate "resources" package, and in the root of directory. I have also tried calling getResourceAsStream() with "file.txt" and "/src/file.txt," but it only works in the above configuration when the file is with the .class files. Any tips would be much appreciated!
Why not have your file folder inside the tomcat bin and refer the directory from your code. So maven clean will not alter the files and you can remove, update file without needing to restart the application. ( here i have file inside etc )
Path: /Users/username/Documents/apache-tomcat-8.5.15/bin/etc
ArrayList<String> readList = null;
String workingDir = System.getProperty("user.dir");
String fileName = "File.txt";
File file = new File(workingDir+"/etc/" + fileName);
readList = resourceReader.readFile(file.getAbsolutePath());
I have method readFile to parse some data and build the ArrayList in the above example.
Read about System Properties
Turns out the solution was really simple...I had been trying to manually create a resources folder, but the contents kept being deleted upon building of the jar. Instead, I created a resources package and put the file into the auto-generated folder inside the src folder, which packaged the file into the jar. Thanks everyone!

Java .list() in a jar file

int x = new File("src/Images").list().length;
It works fine for me until I want to run it as an executable jar file.
"/Images" & "Images" won't work and I've read that I can't use new File inside a jar.
I want the jar file to run, locate the file inside and count the amount of images in the folder.
Is there a simple alternative to the above line of code?
I've tried playing with DirectoryStream and a few other things but have had no luck.
Cheers
It usually uses the directory of .jar file as root directory.
The easiest way to "make it work" is this: Having folder src in the same folder as the .jar file and in src folder put the Images folder.
So it looks like this, when you execute the .jar:
...../myproject/myproject.jar
...../myproject/src/Images

How to acces txt file in netbeans build jar file?

So currently my netbeans project folders looks like this:
Block_Breaker <--Project
build
dist
Block_Breaker.jar
nbproject
src
packageONE
packageTWO
data.txt
manifest.mf
applet.policy
build.xml
I want to know how can i acces a data.txt file in packageTWO(when i run Block_Breaker through a jar file and not netbeans). Normally if run through netbeans the following code will work:
FileWriter x=new FileWriter("src/packageTWO/data.txt");
PrintWriter pr=new PrintWriter(x);
But if i run a jar file that netbeans created it doesnt work.
You can't write to that file once it is packaged into a jar file.
Yet reading is still possible using one of the following:
<YourClass>.class.getClassLoader().getResourceAsStream("packageTWO/data.txt");
// or
this.getClass().getResourceAsStream("/packageTWO/data.txt");
witch gives you an InputStream witch you can use to retrieve the content of the file.
If you are required to wite to that file then the simplest way is not to pack it into the jar but have it standalone some where on the filesystem.
More infos about getResourceAstream in the javadoc
This is because your .jar file does not include a folder named src/
Please use ClassLoader.getResource to load resources.

Access a file from a JAR in the same folder

I need to acces (create and read) a file from a JAR file (executable jar),
and that file should be created in the same directory as the JAR
I tried
this.getClass().getResource("myFile")
but since the jar has packages in it, it won't work..
I also tried write just
File f = new File("myFile");
f.createNewFile();
and that works if i execute the JAR from the terminal, but if i execute the JAR by double-clicking it, the file is created in my home directory -.-''
how do i access a file being SURE that that file is in the SAME directory as the JAR file?
(of course also getting the jar absolute path would do the trick since i can get the parent folder from it)
This will give you the full path to the Jar:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
EDIT: sorry, was in javascript mode when I wrote that :). As was so politely requested, in a static method you should be able to do this:
String path = Me.class.getProtectionDomain().getCodeSource().getLocation().getPath();
(where the class name is Me).

Java JAR: Writing to a file

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/

Categories