Writing to properties file from .jar executable - java

I have a problem with writing to properties file via .jar file.
My 'output' works only in Eclipse, but don't know how to change it and make it works in executable .jar.
FileOutputStream output = new FileOutputStream("src/application/data.properties",true);
InputStream in = Login.class.getResourceAsStream("data.properties");
properties.load(in);
properties.setProperty(username+"Username", username);
properties.setProperty(username+"Password", password);
properties.store(output, formattedDate);
EDIT:
I'm getting no errors. I want to store this 'username' and 'password' in data.properties file which is included in a project. When I run it in Eclipse, it works. When I run it by .jar file, it doesn't write those data to properties file. I suppose, it's because when it creates 'output' while running jar, it is created only locally, and it doesn't provide me the access to appropriate file, but I might be wrong. I get this access and I can work on this existing file when I create 'in' by .getResourceAsStream(), but don't know how create 'output' in a similiar way, and be able to store data in already existing file in project.
I create .jar in eclipse by "Export -> runnable JAR file " and run it by double-click.

I'll risk a guess: getResourceAsStream is returning a Stream reading the properties file inside the JAR, while FileOutputStream is addressing a file outside the JAR - the properties inside the JAR is never changed!
It is not trivial to overwrite a file inside a (running) JAR! The Jar must be recreated for that. Probably better only write/read from an external file, that is, use FileInputStream instead of getResourceAsStream. It's also a bit strange to access a file in the "src" directory since this normally is not included in the deployed system/code.
Using FileOutputStream(..., true) is appending the data to the end of file - it is not overwriting the data for an existing user. Not sure if that is a problem or if this code is only called for new users?!
saving clear passwords (file or database) is a potential security threat...

Related

Java FileNotFoundException when trying to read txt file from resources folder

I'm trying to read a text file located in src/main/resources/test/file.txt. I'm trying to get the path of the file using String path = getClass().getResource("/text/file.txt").getFile(); but when I try to read it I get a FileNotFoundException. I tried putting many different paths, all of which failed. How can I go about doing this?
The idea of putting something into the src/main/resources tree is that it will be copied into the JAR file that you build from your project. It will then be available to your application via the Class methods getResource(String) and getResourceAsStream(String) methods.
When you are running in your application in the development environment, it is certainly possible to use FileInputStream etcetera to access the resource. But this won't work in production. In production, the resources will then be inside your app's JAR file. FileInputStream cannot open a JAR file and its contents by name.
When you do this:
getClass().getResource("/text/file.txt");
you get a URL for the resource, which will look something like this:
jar:file:/path/to/your.jar!/text/file.txt"
It is not possible to turn that into a pathname the FileInputStream will understand. Whatever you try will give you a FileNotFoundException ... or something that is not the resource you want to read.
So what to do?
You have a few options, depending on your application's requirements.
You can use getResourceAsStream and use the resulting input stream directly.
You can copy the contents of getResourceAsStream to a temporary file, and then use the pathname of the temporary file.
You can create an application specific directory (e.g. in the user's home directory) and extract the file you need from the JAR into the directory. You might do this the first time the application runs.
You could open the JAR file as a JarFile and use that API to open an InputStream for the resource. But this assumes that that the resources are in a JAR ... and on some platforms (e.g. Windows) you may encounter problems with file locking. (And it would be a bad idea to attempt to update the resource in the JAR.)
Try giving complete path of the file from the disk.
C:\Users\MyUser\Desktop\file name with extension

JAR file that reads .cfg file and produces a text file

I developed a small program that takes as input some configuration parameters from a .cfg file and produces an output .txt file based on the values taken from the .cfg file.
While the program runs perfectly in eclipse, I receive a NullPointerException error when I create a JAR file of this program and try to run it. From my understanding I have to make the JAR access its internal files or try to receive the needed information (in this case the .cfg file) externally, e.g. create a resource folder next to the JAR file.
I have searched many related questions asked here but I got even more confused whether there is an optimal way to produce a JAR file that can access input files and produces output files. Should I modify my code to achieve this or there is another way?
For the record, I use FileReader and FileWriter to access and produce the files.
If your .cfg file is outside of the JAR file, it should work just as in Eclipse.
If you want to access it from inside of the JAR archive, then you should use a class loader to load it, instead of FileReader...

Referencing file from within the same JAR file as the application

I have a Java application in Eclipse that references .XML files as templates for other functionality. Usually I package the .JAR file without these files, because placing them within the same folder as the .JAR file seems to work fine with this reference:
File myFile = new File("templates/templateA.xsd");
I now require that these templates be placed within the same .JAR file as this application. I can include them with no problems, but these references no longer seem to work.
Is there a correct way of referencing the .XML file from within the same .JAR that the application is running from?
You need to know how to load the files from class path.
one of the ways is as follows
class XMLLoader {
public String loadXML(String fileName){
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
// do the loading of the file from the given input stream.
}
}
you know that the "templates" folder should be inside of your jar.
If you just need to read this file, you might not need a java.io.File but just an InputStream that you can get via
this.getClass().getResourceAsStream("templates/templateA.xsd")
If you really need a java.io.File... I do not know... The last time a really needed a File, I just copied the InputStream to a temporary file but this is ugly.

file load in a jar

I'm loading a prop and saving it
File propfile=new File(getClass().getResource("credentials.properties").toURI());
prop.load(new FileInputStream(propfile));
prop.setProperty("a", username);
prop.setProperty("c", password);
prop.setProperty("b", pbKey);
prop.store(new FileOutputStream(propfile), null);
When i normally run this in netbeans its fine, when its bundled into .jar file it throws
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.(Unknown Source)
now when i use
getClass().getResourceAsStream("credentials.properties");
i can read the file , but i can't save the file unless i use the .toURI()
as in -> Storing changes in .properties file that has been read via getClass().getResourceAsStream
so when i use toURI() and when i run it (jar file) it would cry out saying the URI is not hierarchical
and when i use getResourceAsStream , i couldn't save the file
what should i do?
the properties file is in same package as class is in.
If you only need to load the properties, you shouldn't be using File at all - you should use getResourceAsStream.
If you need to save the properties back again, you can't easily have them in a jar file. You'd need to rebuild the jar file each time you save - ick!
If you really need both, you might want to consider having a file which is created the first time you need to save changes: when loading, use the file if it's present, but use the version in the jar file otherwise.
EDIT: If you're building a desktop application and these are basically user preferences, you should look into the Preferences API. Also be very careful if you're storing passwords... avoid doing so if you possibly can.
Try:
File userFile = new File(System.getProperty("user.home"), "myProgram.properties");
if(userFile.exists()) {
prop.load(new FileInputStream(userFile));
} else {
prop.load(getClass().getResourceAsStream("credentials.properties"));
}
prop.setProperty("a", username);
prop.setProperty("c", password);
prop.setProperty("b", pbKey);
prop.store(new FileOutputStream(userFile), null);
(be aware that user.home does not work every time on every machine, but it should work next to every time.)

Setting Path Directory on File Reader

I'm working with text files on Java. On Ubuntu 10.
But, I'm having problems with path dir.
Example:
saveFile("textFile.txt","abc");
This abstract function basically put "abc" on "textFile.txt".
I compile this file, and create a jar file (using NetBeans).
When I run the app, and call saveFile("textFile.txt","abc"), textFile.txt is saved on \home. I don't want this. I want that textFile.txtgo to pathDir inside jar file.
How do I write in this file, this same way?
When reading resources from a JAR file, you cannot use the File API. Instead, you use Class.getResourceAsStream(), like this:
reader = new InputStreamReader(MyClass.class.getResourceAsStream(
"/apathdir/textFile.txt"), "UTF-8");
Note also how the encoding is specified. FileReader does not allow that, which is why it should usually be avoided.
Iwant to know, if fileName =
"textFile.txt", what is the path dir
of this file?
If you only use a bare file name (without giving a directory), the JVM will look for the file in the current directory of the JVM process; that is usually the directory you ran the JVM (the java executable) from.
how do i do to set
/apathdir/textFile.txt?. apathdir is a
directory that is inside jar file.
I tried: fileName = "/apathdir/textFile.txt", but doesn't works.
If you want to load a file from inside a JAR file, you cannot load it using FileReader. You need to use ClassLoader.getSystemResourceAsStream() (or Class.getResourceAsStream). See e.g. this article for an explanation:
http://www.devx.com/tips/Tip/5697

Categories