Reading text file from outside a JAR file? - java

I am able to read and alter a text file whilst in Eclipse, however when exported as a "Runnable JAR" it no longer works, it seems to me that the relative path is from inside the JAR, not to the JAR.
BufferedReader bufferedReader = new BufferedReader(new FileReader("RELATIVE PATH"));
I want it so that if I export my program as program.jar, and have file.txt in the same folder as program.jar, it opens file.txt if that is the relative path set.
Thanks for any help.

You can fetch the directory of your .jar file according to the solution of this answer and make your file accesses relative to that directory.
Beware of the warning concerning loading your class from a non-file location!

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!

Where the file will be located while using IO Streams in Java In Eclipse IDE?

I want to print the output in a file. I am using PrintWriter IO stream to add the data to file. When I want to check it, I don't know where the file is located. I am using Eclipse IDE.
PrintWriter writer=new PrintWriter("output.txt","UTF-8");
writer.println("Barcode Reader");
So can any one point me to where the file will be located?
I had this problem initially when I switched to using Eclipse. The current relative path is set to the project directory. The following code snippet will explain this better.
Path currentRelativePath = Paths.get("");
String myPath = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + myPath);
Note that the Path object is received from a get method in Paths((plural)). They are located in java.nio.file.
Further information about this can be found in the Path Operations page.
Does that solve your problem?
It will be present in your project's root folder.
Just open your project folder from your workspace using Explorer and it will be there.
With a filename like "output.txt" it will be placed into the current working directory.
Unless you specify otherwise, in Eclipse that will be the root directory of your project.
You may have to click "Refresh" for it to show up in the File Explorer.
If you give you file name directly like C:\java\workspace\ocpjp7 (a Windows
directory) or /home/nblack/docs (the docs directory of user nblack on UNIX), you can find your file in those directories. But if you don't give the full path, it will be in your current working directory.
"output.txt" -> root
"src/resources/output.txt" -> in resources package
At first you should create this file with File in directory you want.Next step to write data into the file. Your file will be located in directory you want , you set when file has created.
Also check this class FileInputStream

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

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

Eclipse-Java: where to put file for Read purpose

I'm programming Java in Eclipse IDE. Here is code I want to read file:
File file = new File("file.txt");
reader = new BufferedReader(new FileReader(file));
I put file.txt in two place:
1) same folder of this SOURCE file.
2) in bin\...\ (same folder of this CLASS file)
But I allways receive NO FILE FOUND.
Please help me.
thanks :)
If the file ships with your application, it would be better accessed as a resource than as a file. Simply copy it to somewhere in your build path and use Class.getResourceAsStream or ClassLoader.getResourceAsStream. That way you'll also be able to access it if you bundle your app as a jar file.
Currently, you're looking for the file relative to the process's current working directory, which could be entirely unrelated to where the class files are.
if you put the file under sources and inside the package "test" for example, the path is:
./src/test/file.txt
you can use
File file = new File("./src/test/file.txt");
System.out.println(file.exists());
The path ./bin/test/file.txt will work in the second case and is more suitable for a normal java project

java.io.FileNotFoundException question

I have a text file text.txt located in the classes output root directory.
When I use new File("text.txt"), i received the java.io.FileNotFoundException.
My output structure is liking
com
mycompany
test.class
text.txt
Anything wrong and how to fix?
When you don't give an absolute location for a file it searches from where you launched the program (your working directory). So, launch your application in the same directory as that file or move the file to where ever you are launching from.
If you want to read a file relative to your classpath however, you need to do something like this...
reader = new BufferedReader(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("test.txt")));
It will use the current working directory. From the Java documentation (http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#File%28java.lang.String%29):
By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.
new File("text.txt") is relative to your working directory. You could use this.getClass().getResourceAsStream("text.txt") to load a file from the classpath.

Categories