How can a value be stored before the jvm exits? - java

When my program exits I want to store an integer value that is loaded again when theh program starts.
Is serialization an option?

You have following options:
Serialize and store the value in a file and read it when you restart the application.
Store it in DB before closing app and reload when restarting the app.

Yes you need to look into serialization.
Serialization helps you write the state of the object in a file
Use deserialization when you want to read the state of the object.

Serialization is definitely an option. In the init of your class having the variable, you have to load the value from somewhere (server, file, etc.). Since its that simple (one int) I suggest to load it from the file or Properties.
Take a look at this Properties example:
http://www.mkyong.com/java/java-properties-file-examples/

So, you want a variable to retain its value between program executions. Save it to a file at program exit and attempt to read it from the same file at program startup (or initialize it to a default value if the file isn't there).

You could store it to a .txt file and have it read it back in and set the variable.

Related

Android Variables in Background

I'd like to know how I can set a variable that will stay the same after I have closed the app. In this case I don't want to make it with a SharedPreference or a DataBase.
Thanks in advance.
If the app gets closed any variable will be long gone on the next start.
The only way to keep data is to use persistence of some sort, and the most commonly used one is SharedPreferences.
You can alternatively write to a file, send your data to a server (and load it again on the next start), or use a database.
You can also make use of a Service which you keep running in the background, that keeps your values. But you will have no guarantee about when / how the system might stop it, and they would be lost—again—like before.
If you want to keep some value, you need to persist it.
Variables endure for the life cycle of an app. When user closes an app and that app is not running a service in the background everything is deleted. In some occurences(but this has a slight chance) static variables from previous session can be read incidentally if app is restarted again, but this is not a correct behaviour.
There are 3 ways to keep your data.
Write to file: You can create files in txt, json or in any other format you wish, and read from these files on runtime to get values from previous session. I don't prefer writing to file to keep data very much. If you don't know how to use database and want mess with it, you can use this.
Shared Preferences: This is generally for saving settings file with name and value pairs.
Writing to a database: You write your data to database. SQLite and Realm databases are the most popular ones.

Reading an Object from environment.getProperty()

I am trying to read from environment.getProperty(). I am able to read to pass in a key and retrive, but now i am trying to read an object(so as to make the code generic).
So environment values are loaded from a JSON.
say:
{name:"xyz",class:"12"}
so when I pass in environment.getProperty("name") I get back xyz.
But I want to read something of this nature.
{student:[student1:{name:"xyz",class"12"}, student2:{name:"abc",class:"11"}]}
I tried using environment.getProperty("student",List.class) but that didn't resolve this.
Any comments?

Monitor text file for changes in Java

I am trying to monitor a text file for a change in the one line of text it contains. The file is constantly being deleted and created with the same name and path but the content rarely changes.
I am trying to construct an if statement so that if the content of the file changes then the system will print to the console.
I have looked at this Stack Overflow question and tried using the java-diff-utils example found on this page, but I could not find a way to implement it to solve my problem.
Start by generating an MD5 of the original file, then using a background Thread, recalculate the MD5 and compare it with the original. When the hash changes, the file contents would have changed.
Check out MD5 Hashing Example
If you're using Java 7, you could use the Watcher Service to monitor changes to the file. This would replace the thread
"High-level" advice: you could...
Consume the file contents in a custom Object at app initialization, and store it in a static variable
Define a property for said object, returning a String which represents the contents of the file
Use a TimerTask to periodically instantiate a new instance of said custom Object representing the file, and...
... compare the two String properties, so that you can print out the
latter should they not be equal, and then overwrite the static variable's value with the newly instantiated object
Note that this is hardly the professional way to handle recurrent tasks or file comparison - it's just meant to give you a draft direction.

Java Serialization - Recovering serialized file after process crash

I have a following usecase.
A process serializes certain objects to a file using BufferedOutputStream.
After writing each object, process invokes flush()
The use case is that if the process crashes while writing an object, I want to recover the file upto the previous object that has been written successfully.
How can I deserialize such file? How will Java behave while deserializing such file.
Will it successfully deserialize upto the object that were written successfully before crash?
While reading the last partially written object, what will be the behavior. How can I detect that?
Update1 -
I have tried to simulate process crash via manually killing the process while objects are being written. I have tried around 10-15 times.Each time i am able to deserialize the file and file does not has any partial object.
I am not sure if my test is exhaustive enough and therefore need further advice.
Update2 - Adam had pointed a way which could simulate such test using truncating the file randomly.
Following is the behavior observed for trying out around 100 iterations -
From the truncated file ( which should be equivalent to the condition of file when a process crashes), Java can read upto last complete object successfully.
Upon reaching the last partially written object, Java does not throw any StreamCorruptedException or IOException. It simply throws EOFException indicated EOF and ignores the partial object.
Each object is deserialized or not before reading the next one. It won't be impacted because a later object failed to be written or will fail to deserialize
I suspect you are misusing java serialization - it's not intended to be a reliable and recoverable means of permanent storage. Use a database for that. If you must, you can
use a database to store the serialized form of java objects, but that would be pretty inefficient.
Yeah, testing such scenario manually (by killing the process) may be difficult. I would suggest writing a test case, where you :
Serialize a set of objects and write them to a file .
Open the file and basically truncate it at random position.
Try to load and deserialize (and see what happens)
Repeat 1. to 3. with several other truncate positions.
This way you are sure that you are loading a broken file and that your code handles it properly.
Have you tried appending to ObjectOutputStream? You can find the solution HERE just find the post where explains how to create an ObjectOutputStream with append.

Java Hashmap where the Key is a File and the Value is a Model

I'm working on a project where I have a hashmap with the key as a File object in Java IO library and a custom model object, called a DrawingModel as the value in the hashmap. When I change the model, I need to save the file. When I go through the following sequence of events:
I open a File
I do some changes
I save that file (File -> Save)
I Exit the file
I then Open that same file
However, it does not open!
My question is if I change the file (by saving) do I need to remove that key value pair from the Hashmap and add a new key value pair? Such that the value is the same but the keys are updated?
Thank you very much for your time and help!
Sincerely,
nc5
The File object is little more than a wrapper to the path of the actual file. It does not lock your files in any way.
The locking is caused by some stream that is still open. I bet you are not closing your outputstream after saving into the file.
I suggest you put the file Name as the Key instead of the File Object and handle the file editing/updating stuff through another logic. A file object as key doesn't make much sense.
Yes. If you think logically, your key is changed. And once it is changed, you would no more able to locate your data using that. You should insert a (new key, value) pair in your map.
Always close() the file that you opened, else the file will not be updated. And it will be also better to close the Connection and Channel streams
Make sure you have closed the file stream (most upper one). I.e if you have opened several streams one over another, then make sure the top-most stream is closed. Otherwise the file will be locked by the operating system.

Categories

Resources