Showing posts with label java jar wirte read. Show all posts
Showing posts with label java jar wirte read. Show all posts

Tuesday, 19 November 2013

Read or write from file inside a jar! What hell!

In my last "session" of java code I found myself in this problem: I must read and write from a file inside a jar. In detail i have a project that using this jar and from this project I must to interact with file.
Initially I thinked "oh it will very easy" but how wrong I was. The first problem is this:
How I can reference to file inside a jar? 
We must think that we cannot reference with an absolute or machine path: the project can be runned in hundreds of machines with hundreds of difference paths. So we must use a internal project path. Good. As first thing, read from this file. Java provides a fantastic method that which allows us to get an input stream from file with ponly passing as a parameter the name of file without the absolute path. For example: if my file inside jar has this name "pippo.txt" i can get an InputStream with this method:
getClass().getClassLoader().getResourceAsStream("pippo.txt")
To read the file,do this:
 InputStream stream = getClass().getClassLoader().getResourceAsStream("pippo.txt");
 String sCurrentLine;
BufferedReader br = new BufferedReader(new InputStreamReader(stream ));
          StringBuilder string = new StringBuilder();
while ((sCurrentLine = br.readLine()) != null) {
string .append(sCurrentLine);
}
string.toString();
Easy right? :)
But if I want to write inside a jar? This is a almost "impossible" task. You must think that a file inside a jar is as a file inside a .zip or .rar. Can you write a file inside a compress file? Yeah! But you must unzip the file, write the file and compressagain the entire package. In the same way works a file inside a jar. First you must extract all content of jar file, second you must write into file and third you must re-create the jar file and all of this operation you must do into your java code. It is an hell!
Usually the files inside a jar are a properties files: file that can be read and writed from other classes. But these files are special files: their are not a common files.  If you think that for your application there is a file that can be write as text file, you should think a way to create this file outside of jar. For example you can say to a class inside a jar to produce a file at runtime execution to  store in file system , save the path of file (you cannot save it on jar for the same problem described above: you cannot write inside a zip file.)and then the project that used this jar can ask to class to retrieve the path of this file and finally he can modify it.