Confused about "files inside a JAR"
I have a program that has a Properties file which I would like to "save" into the JAR file, so it is not outside the JAR.
I know this can be done, because I've seen some Java programs that save their configuration between sessions, but not via a file inside its directory. This leads me to believe the file is maintained within the JAR itself, which would be REALLY handy and secure.
Is this a correct assumption? If so, how would I do it? Here's a "test program" that we can play with, how would I save MyProperties' properties field into the MyProgram JAR?
package SBX;
import java.util.*;
import java.io.*;
publicclass MyProgram{
// Instance Variables
public MyProperties myProp =new MyProperties();
public String stringOne ="Will this be loaded?";
public String stringTwo ="How about this one?";
// Main Method
publicstaticvoid main(String[] args){
new MyProgram();
}
// Constructors
public MyProgram(){
if ((new File("properties.txt")).exists()){
myProp.updateProgram(this);
}
System.out.println("1) " + stringOne);
System.out.println("2) " + stringTwo);
myProp.updateProgram(this);
System.out.println("3) " + stringOne);
System.out.println("4) " + stringTwo);
myProp.updateProperties(this);
// -- //
// Now that we've "updated" stringOne & stringTwo and "updated" myProp and saved it,
// we should be able to get the values "ONE" and "TWO" for print outs 1 & 2 when we next
// run the program, instead of "Will this be loaded?" and "How about this one?", as we got during the first run.
// However, the thing I need help with is saving the Properties to the JAR file so it's not accessable
// outside of the JAR file. How can this be done?
}
}
class MyProperties{
// Instance Variables
private Properties properties;
// Constructors
public MyProperties(){
Properties defaults =new Properties();
defaults.setProperty("stringOne","ONE");
defaults.setProperty("stringTwo","TWO");
properties =new Properties(defaults);
try{
FileInputStream fis =new FileInputStream("properties.txt");
properties.load(fis);
fis.close();
}
catch (Exception e){
System.out.println("No properties file found, ignore this; one will be saved when the program exits.");
}
}
// Methods
publicvoid updateProgram(MyProgram prg){
prg.stringOne = properties.getProperty("stringOne");
prg.stringTwo = properties.getProperty("stringTwo");
}
publicvoid updateProperties(MyProgram prg){
properties.setProperty("stringOne", prg.stringOne);
properties.setProperty("stringTwo", prg.stringTwo);
try{
FileOutputStream fos =new FileOutputStream("properties.txt");
properties.store(fos,"A header");
fos.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
Thanks for any help!
PS...writing demo programs is kind of fun :)

