Java config.properties file won't save - java

I have the following class that should allow to:
Send the caller the value of a property,
Set a new value for a property and save the Property file.
Sending the value of a property works.
Setting a new value for a property, and saving the file, that part don't work.
What is wrong?
I already searched a lot and many different ways are discussed everywhere, nothing that can help me. That's why I have to ask here.
Many thanks to anybody who can help me!
public class Config {
private Properties props = new Properties();
private String strFilePath = "Config.properties";
private File configFile = new File(strFilePath);
public Config(){
try {
InputStream in = Config.class.getClassLoader().getResourceAsStream(strFilePath);
props.load(in);
}catch(IOException ex){
System.out.println(ex);
}
}
public String getPropriete(String sPropriété){
String strResult = "";
try{
strResult = props.getProperty(sPropriété);
}catch(Exception e){
System.out.println(e);
strResult = "";
}
return strResult;
}
public void setPropriete(String sPropriété, String sValeur){
try{
System.out.println(sPropriété + " --> " + sValeur);
props.setProperty(sPropriété, sValeur);
FileOutputStream fos = new FileOutputStream(strFilePath);
props.store(fos, null);
props.save(fos, null);
Writer out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
out.flush();
out.close();
fos.close();
}catch(Exception e){
System.out.println(e);
}
}
}

Just do this:
try{
System.out.println(sPropriété + " --> " + sValeur);
props.setProperty(sPropriété, sValeur);
FileOutputStream fos = new FileOutputStream(strFilePath);
props.store(fos, null);
fos.close();
}catch(Exception e){
System.out.println(e);
}

Related

Improper Resource Shutdown or Release

Description:
In the code below What am i doing wrong in the code below, in my code audit i got improper resource shutdown or release.
I tried taking out the close and flush from the code below
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
fos.flush();
fos.close();
Main code:
FileOutputStream fos=null;
try {
Hashtable hash = responseBlob.getAllAttachments();
Enumeration e = hash.elements();
while (e.hasMoreElements()) {
SBADataAttach tmpAttach = (SBADataAttach) e.nextElement();
String tag = tmpAttach.getTag();
byte[] data = tmpAttach.getData();
// encode compressed file
if (hasTag(tag))
mimeResponse.addPart(tag, Base64.encodeBytes(data)
.getBytes());
else
mimeResponse.addPart(tag, data);
try {
if (this.configData.getBlobPath() != null)
{
// save compressed file
String fileName = File.separatorChar + "tmp"
+ File.separatorChar + tag;
Log.theLogger.debug("XisServlet.process() ... "
+ "Save compressed file = " + fileName);
File someFile = new File(fileName);
fos = new FileOutputStream(
someFile);
fos.write(data);
fos.flush();
fos.close();
}
} catch (Exception zipe) {
Log.theLogger.error(zipe.getMessage(), zipe);
}
}
} catch (SBADataException sde) {
// cannot detach files from blob
Log.theLogger.error(sde.getMessage(), sde);
}
finally {
try {
if( fos!=null ) {
fos.close();
}
} catch(IOException e) {
Log.theLogger.error(e.getMessage(), e);
}
}
I don't get any error. But in the Appsec finding i getImproper Resource Shutdown or Release
try{
//open resources
File someFile = new File(fileName);
fos = new FileOutputStream(someFile);
fos.write(data);
}
catch(Exception e1){
//handle exception
}finally{
//close resources
fos.flush();
fos.close();
}
}

How to saving a HashMap to a file in Android?

I'm trying to save user settings to a file, from where I can read the later. But I cant get it to work properly. I've tried reading up on this, but I'm still having problems.
Map<String, String> userSettings = new HashMap<>();
public void updateUserSettings(){
userSettings.clear();
userSettings.put("item0", item0);
userSettings.put("item1", item1);
userSettings.put("item2", item2);
userSettings.put("item3", item3);
userSettings.put("item4", item4);
userSettings.put("item5", item5);
userSettings.put("item6", item6);
userSettings.put("item7", item7);
userSettings.put("i0", Float.toString(i0));
userSettings.put("i1", Float.toString(i1));
userSettings.put("i2", Float.toString(i2));
userSettings.put("i3", Float.toString(i3));
userSettings.put("i4", Float.toString(i4));
userSettings.put("i5", Float.toString(i5));
userSettings.put("i6", Float.toString(i6));
userSettings.put("i7", Float.toString(i7));
userSettings.put("huvudMaskin", huvudMaskin);
userSettings.put("minorMaskin1", minorMaskin1);
userSettings.put("minorMaskin2", minorMaskin2);
userSettings.put("maskinTid", Float.toString(maskinTid));
writeSettings();
}
public void writeSettings() {
try
{
FileOutputStream fos = context.openFileOutput("test.ser", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userSettings);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readSetttings() {
try
{
FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"test.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map myHashMap = (Map)objectInputStream.readObject();
userSettings = null;
userSettings = myHashMap;
}
catch(ClassNotFoundException | IOException | ClassCastException e) {
e.printStackTrace();
}
executeSettings();
}
I have both read and write rights to the app.
Im not getting anything out of this. I've checked the hashmap, and it works as intended. I have also tried a lot of different approaches, and the only thing I managed to get working was saving strings to a .txt file.
private String subFolder = "/userdata";
private String file = "test.ser";
public void writeSettings() {
File cacheDir = null;
File appDirectory = null;
if (android.os.Environment.getExternalStorageState().
equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = getApplicationContext().getExternalCacheDir();
appDirectory = new File(cacheDir + subFolder);
} else {
cacheDir = getApplicationContext().getCacheDir();
String BaseFolder = cacheDir.getAbsolutePath();
appDirectory = new File(BaseFolder + subFolder);
}
if (appDirectory != null && !appDirectory.exists()) {
appDirectory.mkdirs();
}
File fileName = new File(appDirectory, file);
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(userSettings);
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.flush();
fos.close();
if (out != null)
out.flush();
out.close();
} catch (Exception e) {
}
}
}
public void readSetttings() {
File cacheDir = null;
File appDirectory = null;
if (android.os.Environment.getExternalStorageState().
equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = getApplicationContext().getExternalCacheDir();
appDirectory = new File(cacheDir + subFolder);
} else {
cacheDir = getApplicationContext().getCacheDir();
String BaseFolder = cacheDir.getAbsolutePath();
appDirectory = new File(BaseFolder + subFolder);
}
if (appDirectory != null && !appDirectory.exists()) return; // File does not exist
File fileName = new File(appDirectory, file);
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(fileName);
in = new ObjectInputStream(fis);
Map<String, String> myHashMap = (Map<String, String> ) in.readObject();
userSettings = myHashMap;
System.out.println("count of hash map::"+userSettings.size() + " " + userSettings);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(fis != null) {
fis.close();
}
if(in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Your problem is very simple: you are using two different file names when writing the data resp. reading it.
FileOutputStream fos = context.openFileOutput("test.ser", Context.MODE_PRIVATE);
vs.
FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"test.ser");
And, most likely, your reading code did throw an IOException at you, telling you something about trying to open a file that doesn't exist.
Thus, the real take-away/answer here: read those exception messages very carefully. Typically, they tell you exactly what the problem is!
Change these lines :
public void readSetttings(){
String path=context.getFilesDir() + File.seprator + "test.ser";
if(! new File(path).exists() ){
//throw NullPointerException ;
//return;
/*
*you can choose one of these
*pay attention : when choose NullPointerException you shold add throws Exceptions on your method
*/
}
try{
FileInputStream fileInputStream =context.openFileInput("test.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map myHashMap = (Map)objectInputStream.readObject();
userSettings = myHashMap;
}catch(ClassNotFoundException | IOException | ClassCastException e) {
e.printStackTrace();
}
executeSettings();
}
If it is only primitives that you want to store then you should be using SharedPreferences which Android provides out of the box.
public static final String PREFS = "usersettings";
#Override
protected void onCreate(Bundle b){
.....
// read user settings on start
SharedPreferences settings = getSharedPreferences(PREFS, 0);
int someId = settings.getInteger("someId", 0);
setSomeId(id);
}
#Override
protected void onStop(){
.....
SharedPreferences settings = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInteger("someId", mSomeId);
// commit changes on exit
editor.commit();
}

Java - Setting Value in Properties File is Overwritting Previous Values

I have a class that manages all the settings with methods:
public class SettingsManager {
public String settingsFileName = Start.programName + ".settings";
public SettingsManager(String settingsFileName) {
this.settingsFileName = settingsFileName;
}
public void saveIntoNewSettings(String nameOfSetting, String settingValue) {
Properties programProperties = new Properties();
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(this.settingsFileName);
programProperties.setProperty(nameOfSetting, settingValue);
programProperties.store(outputStream, null);
outputStream.close();
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to save a setting into the file " + this.settingsFileName + ".");
}
}
public void saveSetting(String nameOfSetting, String settingValue) {
try {
InputStream inputStream = new FileInputStream(this.settingsFileName);
OutputStream outputStream = new FileOutputStream(this.settingsFileName);
Properties programProperties = new Properties();
programProperties.load(inputStream);
inputStream.close();
programProperties.setProperty(nameOfSetting, settingValue);
programProperties.store(outputStream, null);
outputStream.close();
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to load a setting from the file " + this.settingsFileName + ".");
}
}
public String loadSetting(String nameOfSetting) {
Properties programProperties = new Properties();
InputStream inputStream = null;
try {
inputStream = new FileInputStream(this.settingsFileName);
programProperties.load(inputStream);
inputStream.close();
return programProperties.getProperty(nameOfSetting);
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to load a setting from the file " + this.settingsFileName + ".");
}
return "";
}
public boolean settingsFileExists() {
File settingsFile = new File(settingsFileName);
if (settingsFile.exists() && !settingsFile.isDirectory()) {
return true;
}
else {
return false;
}
}
}
After creating an instance of this class named "mainSettings", I run these two lines of code in my main class:
mainSettings.saveSetting("hello1", "world1");
mainSettings.saveSetting("hello2", "world2");
In my settings file, all I see is this:
hello2=world2
For some reason every time I call the saveSetting method it gets rid of older values in the settings file. I thought that those values should be saved when I called "programProperties.load(inputStream);".
When you create the OutputStream the file is being truncated to 0 bytes. Infect you do not have any properties read. Try this:
public void saveSetting(String nameOfSetting, String settingValue) {
try {
InputStream inputStream = new FileInputStream(this.settingsFileName);
Properties programProperties = new Properties();
programProperties.load(inputStream);
inputStream.close();
OutputStream outputStream = new FileOutputStream(this.settingsFileName);
programProperties.setProperty(nameOfSetting, settingValue);
programProperties.store(outputStream, null);
outputStream.close();
}
catch (Exception errorException) {
Common.errorEncountered(errorException, "An error occured while trying to load a setting from the file " + this.settingsFileName + ".");
}
}
Should solve your issue.

java write records to new line of file

every time the code runs i want the new record to be added to a new line
as it is when a new record is added it will write over previous line
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(getApplicationContext(), "File Saved", 0).show();
} catch (IOException e) {
e.printStackTrace();
}
}
You need to write the "newline" character as well when writing data:
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.write(System.getProperty("line.separator"));
} catch (IOException e) {
e.printStackTrace();
}
}
But be careful with writing binary data like this. It's better to use e. g. BufferedWriter to write string data:
BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));
writer.write("Hello world!");
writer.newLine();

Checking if file exists, if so, dont create new file and append instead

private void saveFormActionPerformed(java.awt.event.ActionEvent evt) {
name = nameFormText.getText();
surname = surnameFormText.getText();
age = Integer.parseInt(ageFormText.getText());
stadium = stadiumFormText.getText();
Venues fix = new Venues();
fix.setName(name);
fix.setSurname(surname);
fix.setAge(age);
fix.setStadium(stadium);
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
This is what I have so far. Any ideas on what I could do with it to append the file if it's already created?
You have first to check if the file exists before, if not create a new one. To learn how to append object to objectstream take a look at this question.
File outFile = new File("output.data");
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
if(!outFile.exists()) outFile.createNewFile();
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
Using Java 7, it is simple:
final Path path = Paths.get("output.data");
try (
final OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
final ObjectOutputStream objOut = new ObjectOutputStream(out);
) {
// work here
} catch (IOException e) {
// handle exception here
}
Drop File!

Categories