Monitor text file for changes in Java - 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.

Related

Java serialization, how identify and name one file for each object?

I want to save severals files using Stream to serialize objects, with one serializable object per file.
The reason why I want have one file per object is that I have a list of these objects, I am on Android and at the start of the applicaiton I want load all saved objects, this is the easy part.
But during the execution I want add new elements in this list, and delete elements. And I want update the folder with my files in the same time.
So I supposed I have to create one file per object. But may be there is another solution ?
The main problem is : how name each file ? To avoid overwrite a file, ...
I first thinked that I will have to name my files depending the name of a String given by the user, but I will have to check if the name file is valid,...
So may be the solution is to just name my files with an integer, and at the first load, I just continue the counter from the higher file ?
I suppose my problem is frequent, so what are your solutions to write during the execution a dynamic list of objects ?
Thanks you

How can a value be stored before the jvm exits?

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.

Java - overwriting specific parts of a file

I would like to update specific part of a text file using Java. I would like to be able to scan through the file and select specific lines to be updated, a bit like in a database, for instance given the file:
ID Value
1 100
2 500
4 20
I would like to insert 3 and update 4, e.g.
ID Value
1 100
2 500
3 80
4 1000
Is there a way to achieve this (seemingly) easy task? I know you can append to a file, but I am more interested in a random access
I know you can append to a file, but I am more interested in a random access
You're trying to insert and delete bytes in the middle of a file. You can't do that. File systems simply don't (in general) support that. You can overwrite specific bytes, but you can't insert or delete them.
You could update specific records with random access if your records were fixed-length (in bytes) but it looks like that's not the case.
You could either load the whole file into memory, or read from the original file, writing to a new file with either the old data or the new data as appropriate on a per line basis.
You can do so using Random Access files in java where you can place your current write and read position using available methods. you can explore more here
Load the file into memory, change your value, and then re-write the file
if there's a way to insert into a file without loading it, I haven't heard of it. You have to move the other data out of the way first.
unless you're dealing with huge files, frequently, performance isn't too much of a concern
As said by the previous answers, it's not possible to do that symply using streams. You could try to use properties, that are key, value pairs that can be saved and modified in a text file.
For example you can add to a file a new property with the command
setProperty(String key, String value)
This method adds a new property or, if already existing, modifies the value of the property with the choosen key.
Obviously, new properties are added at the end of the file but the lack of ordering is not a problem for performances because the access to the file is made with the getProperty method that calls the Hashtable method put.
See this tutorial for some examples:
http://docs.oracle.com/javase/tutorial/essential/environment/properties.html

Java - Unable to Detect Files

Following on from my previous question, my program doesn't detect the 300 images that have just been created in a particular directory; instead, it only detects desktop.ini, which is not the case as I can physically see that the files have been created within said directory and do exist.
Can somebody please explain why this happens as when I run the program the next time, it seems to work just fine?
The only way that something is detected within the directory on the first run is when there is at least one file which exists in the directory before the program is compiled and executed.
Many thanks.
UPDATE: Files are detected as follows:
//Default greyscale image directory (to convert from greyscale to binary).
static File dirGrey = new File("test_images\\Greyscale");
//Array of greyscale image filenames.
static File imgListGrey[] = dirGrey.listFiles();
without knowing how you create the images, this question is akin to 'How many kittens are under my desk right now?'
Are you creating the files yourself? If so, are you closing any file handles referring to those files once they are created?
You're creating the file list in a static array, and it's created when the class containing the array is loaded by the Java class loader, which is probably before you create the image files. That's why the array contains an outdated list.
static is rarely needed, mostly useful for constants (things that never change, such as 42), for pure functions (Math.sqrt()) and a few other special cases. When you use it, you have to learn all the tricky initialization order stuff. Otherwise, just stick with non-static variables.

How to get address of a Java Object? [duplicate]

This question already has answers here:
Is there a way to get a reference address? [duplicate]
(5 answers)
Closed 8 years ago.
Is there a way to get address of a Java object?
Where the question comes from?:
At First, I read properties file and all the data from file was placed into table. Properties file can update. So, I want to listen that file. I listen an object using PropertyChangeSupport and PropertyChangeListener.
updatedStatus = new basit.data.MyString();
updatedStatus.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
//After changes "i", we inform the table model about new value
public void propertyChange(PropertyChangeEvent evt) {
Object objec=evt.getNewValue();
tableModel.setValueAt(objec.toString(), 0, 5);
}
});
If updatedStatus changes then i update table. MyString class have private String "Value". I want to listen properties file. So, it should make updatedStatus.value and String of Properties File equal at the same address. If i can do it, so i don't need to listen properties file.
updatedStatus.setValue(resourceMap.getString("HDI.Device.1.Name"));
I tried to use StringBuffer, but i couldn't achieve it. That's why, I asked the question.
Firstly - no, you can't get the address of an object in Java; at least, not pure Java with no debugging agent etc. The address can move over time, for one thing. You don't need it.
Secondly, it's slightly hard to follow your explanation but you certainly won't be able to get away without listening for changes to the file itself. Once you've loaded the file into a Properties object, any later changes to the file on disk won't be visible in that object unless you specifically reload it.
Basically you should listen for changes to the file (or poll it) and reload the file (either into a new Properties or overwriting the existing one) at that point. Quite whether you also need to listen for updates on the string container will depend on your application.
System.identityHashCode(obj) delivers the next-best thing: a number unique for each object. It corresponds to the default Object.hashCode() implementation.
To quote the API: "As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)".
we can get address of an object in memory. Well how? it is like that;
using sun.misc.Unsafe class in java.
create new Unsafe object and use the getAddress(Object); method and it will return a long value that is address.
and also there are many methods for this class.
you can change the values in this address using putInt(Object,long offset, int value) or like this method.(getting some value getnt(Object)).
Note: this class is really UNSAFE . if you make wrong things on your project, JVM will be stopped.
Look into Apache Commons Configuration. This library has support for dynamic reloading of (for example) property files. See here.
The best way to observe if some file changes is IMHO to make a hash value with sha1 or mda5 and save the value in a cache. And you make a Thread that every minutes, seconds, depends how often you watch file changes, and make hash value over the file. So you can compare this two values and if the values are not equivalent so you can reload the new file.
Java not like C/C++. in C++, you will often work with address (that C++ programmer has a concept call pointer). But, I afraid that not in Java. Java is very safe that prevent you to touch its address.
But, there other ways maybe same with your idea is use HashCode. HashCode of an object base on their address on HEAP.

Categories

Resources