Access the folder from jar file - java

I am trying to use a jar file which itself is a web application in another web project. In my jar which i have created using eclipse's export to jar functionality, I have stored owl files in a folder. To use relative paths in the code in the jar I access it using
MyClass.class.getResource("/folderName").getPath();
and this works fine when I deploy (glassfish) and use the project as a separate application. But when I am using the same from within another project, i changed the path like:
BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getResourceAsStream("/folderName"), "UTF-8"));
ArrayList<File> filesFromCommonOntology = new ArrayList<File>();
while(str = br.readLine() != null)
{
File f = new File(line);
System.out.println(f);
filesFromCommonOntology.add(f);
}
for (int i = 0; i < filesFromCommonOntology.size(); i++)
{
file = filesFromCommonOntology.get(i);
String filePath = file.getPath();
Model timeModel = FileManager.get().loadModel(filePath,
ApplicationConstants.N3);
}
But when i run the project i get null pointer exception for line
BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getResourceAsStream("/folderName"), "UTF-8"));
How to resolve this problem?

You cannot enumerate files in a folder when the application is packaged into jar. It is even difficult to imagine how this could work at all: you open a folder as an inptu stream and read the file names (in that folder) that way?
The simplest way would be to add a text file containing entries in the folder, probably with some descriptions. MyClass.class.getResourceAsStream should open files (not folders) from the jar.
If you have very huge number of files, you can also try to reopen own jar as ZipFile and then you can search for the entries in you folder using ZipFile API. However this is more complex.

Related

JAVA :How to Read file in Referenced Libraries

Hi I was reading files using FileReader and Buffereader only and it was working perfectly
fr = new FileReader("C:\\Users\\User\\Documents\\Bus_Station\\Bus station\\tripFile");
br = new BufferedReader(fr);
But I want to read put these files in somewhere so I put them in Referecnced Libraries so I can read from them on any machine without path but it is not working :/
(File file = new File("tripFile.txt");
file.createNewFile();
fr = new FileReader(file););
Any help ?
You should use resources.
URL fileURL = Resources.getResource("test.txt");
String text = Resources.toString(fileURL, Charsets.UTF_8);
How to add a resources folder
How do I add a resources folder to my Java project in Eclipse
adding resources in intellij for java project
How to create resource folder in Netbeans?

Loading files from Resource folder using java jar

I have download.sh file in my src/main/resource folder in maven project and I am reading it through below code
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("download.sh").getFile());
The file is reading when I run this as the standalone application.
If I run this as application using jar ex:-
java -jar runScript.jar SCHEMA_NAME
/Users/IdeaProjects/RunScript/target/file:/Users/IdeaProjects/RunScript/target/RunScripts.jar!/download.sh": error=2, No such file or directory
Can anyone help me in reading file from resource when executing with jar
I think this error happens when you try to read the file. This is because resources inside your jar are not files but streams. So you should use
getClass().getResourceAsStream("download.sh");
and then read that stream, for example:
InputStream resourceStream = getClass().getResourceAsStream("download.sh")
BufferedReader br = new BufferedReader(new InputStreamReader(resourceStream));
String line;
while ((line = br.readLine()) != null) {
// do something
System.out.println(line);
}
I think you are not packaging your resources along with your jar. Please verify your jar contains the resource file (download.sh) with
jar -tvf <yourfile.jar> | grep -i download
Resources are not files. You can get their URLs, or input streams, but nothing you can do will turn a resource in a JAR file into a file on the disk that you can use with File. Short of unpacking the JAR file, that is.

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!

How to open a file independently of the path of the Java project?

I'm working with Eclipse and there, I have Java Project with the name "Test" which also contains text files. A class in this Project should be able to read in one of these files with a BufferedReader. This is my current code for that:
BufferedReader in = new BufferedReader(new FileReader("C:/Users/workspace/Test/testFile.txt"));
My file is always in the Project, but when I move the Project to another path, the file path changes, too, so I have to adjust the code with the new path.
I dont't want that, because it's impractical, so what can I do? How can I get the path of the Project?
You can add file to resources folder and read like
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());
Try something like this:
File currentDirFile = new File(".");
String fileDir = currentDirFile.getAbsolutePath();

Executable Jar file FileNotFoundException

I was having some issues getting the executable jar file for my project to work (outside of the eclipse IDE). I figured out the issue with java -jar fileName.jar
Here's the code:
fileIn = new Scanner(new File("src//resources//TestSave.txt"));
Through a little troubleshooting and research I understand that this wasn't working in the executable jar because it doesn't have a src folder, that's only created within the IDE. Here was my solution:
fileIn = new Scanner(new File("D://resources//TestSave.txt"));
The only problem with this is that if I want to put this program on my resume then who ever views it will have to place the folder into their D drive. I want it to be quick and easy so that they can just view my project with no hassle.
How can I access the resources folder within the executable jar file itself without having to reference/create any outside folders?
You have two options.
put the file in the same file as executable jar fileIn = new Scanner(new File("./TestSave.txt"));
Follow this post reading-a-resource-file-from-within-jar
Use getResourceAsStream (no File) within a JAR:
InputStream inputStream = classLoader.getResourceAsStream("TestSave.txt");
Scanner input = new Scanner(inputStream);

Categories