I have a dialog box that the user inserts various data through gui controls,
and this information is saved as an xml file (implemented in java).
The information stored in the xml file is configuration information
for the application.
I can manually modify the xml configuration file, but I also want to provide this capability through a UI as well.
So when the dialog is opened (for creation of configuration) a corresponding well-defined object is populated by the various values input by the user.
Once the user presses 'save' the information in the object is stored as xml.
Now I was thinking to provide the option for edit the file via UI. So the same dialog is displayed to the user, but this time with the configuration information already filled-in by the loaded file. The corresponding object is populated as well.
I am not sure what is the best way to modify the file at this point.
Should I use 2 objects, 1 that stores all the file's info and 1 that stores the modified values from the dialog, and start comparing the objects for changes so that I modify the file? Or should I delete the file and create a new one?
Which is the best approach, and how would I proceed in each?
Thank you
Consider the data flow. The user will work with the GUI and make changes. The moment they make a modification, the data on the GUI is out of step with the XML. If the user opts to save the data then a simple marshalling operation (trivial if using JAXB) will ensure that the XML is updated. You don't need to compare every field, there's no point - of course you have validated the contents prior to committing them to file. If the user opts to cancel then no marshalling takes place.
There is no need to make a backup and no need to compare what is already in the XML.
However, if the user needs to be able to undo a save (such as revert to previous configuration) then you'll need a backup structure (or maintain a stack of GUI models in memory). I would not recommend that approach, though, as you're just chucking in needless complexity. Users are typically happy with a Save or Cancel button and no Revert.
Keep it simple. Just overwrite the entire file using the updated object. Then you won't need any special code for each case. All you will need is one method to marshall the object into the file and one method to un-marshall it.
Related
I want to create a javafx project, but does it need Database?
when I create this program save these name when I input this name and other. I mean save the result in the program and show me when I run it, I don’t need to be store for along time .just for that time when I will run it?
Short answer is no, JavaFX can run without database and you don't need to use it.
If you need to sava data that only while program is running but don't need to save it for next use of program then you can simply use some Collection or custom data structure to hold what you need in runtime, but bare in mind that this means that all data will reset once you quit program.
If you need to save data even when program shuts down then you will need to use some kind of database, if you want to save a small amount of data then you can use json, xml or even raw txt files, for more data you should take look at some SQL/NoSQL database.
I'm working on an application which is coded in Java. It reads calibration values for later calculations from .xml file on first initialization. Values can be later modified and saved to an xml file from another form called 'Properties', that is opened from the Main form.
How can I notify the Main form after the 'Properties' form is closed to read new modified values from .xml file? Or is there a better way to exchange this data and I should not read .xml again after?
Without more information about how your forms are set up it's hard to give a true answer.
Create an object set up to hold the information you will read from the .xml file. In Main, have one (or more as necessary) of these objects. Store the information from the .xml file into it. Pass and update that data object in Properties form, and have it be returned. After you're done editing, fire a propertyChange or call a method which will trigger tell Main to read from the data store object.
If you want to stick with re-reading the .xml file upon closing the Properties form, then you would need to edit the window/form closing procedure (depends on how your form is set up). If the Properties form is a JFrame, then there should be a "windowClosing" method that can be written for it.
I'm working on this swing project and thought it would be a good idea to save user selections to a text file so whenever program is closed and opened again old selections still persist there. Mainly want to store things like checked checkboxes, radio buttons and some integer variables. Is this possible to do in just plain .txt file or will I have to use something like xml?
This should be done with intention to then grab info from txt file and use to set latest user selections in JFrame.
For this scenario, use the Java™ Preferences API, the page says it:
Applications require preference and configuration data to adapt to the
needs of different users and environments. The java.util.prefs package
provides a way for applications to store and retrieve user and system
preference and configuration data. The data is stored persistently in
an implementation-dependent backing store. There are two separate
trees of preference nodes, one for user preferences and one for system
preferences.
You could use Properties for this, although, creating an object to hold the information and store it in XML using JAXB is also nice and a little more flexible (in my opinion) since the XML structure allows for more of a tree-like structure, allowing for saving more complex information, and for keeping related stuff together. There's no automatic way to do this, and so you the programmer will have to write code for this. If your program is set up as an MVC, Model-View-Control, type program, you'll simply save the model, perhaps via JAXB as I've mentioned.
This is the exact use of property files.
Its just a matter of setting properties and saving to a property file and getting these properties at load time. Define the items you need saving in key value pairs when saving. You can retrieve from the key when reading.
For example for a radio button have the property write as ;
prop.setProperty("radioselected", "true"); //true or false based on the selection
When reading,
boolean radioSelected = Boolean.parseBoolean(prop.getProperty("radioselected"))
If this value is true, set the radio button checked state true when loading the UI. If not keep it unchecked.
Refer http://www.mkyong.com/java/java-properties-file-examples/ for more details.
You can use regular text files. It's only a matter of encoding the data from your program into text and decoding the text into the form when loading.
As the other answers suggest, you can also use properties to not reinvent the wheel.
Use properties file. To save it when window is closing use code like following:
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
saveProperties();
}
});
Writing Java objects or a List into a text file is ok. But I want to know how I can update or rewrite a object which was written previously without writing objects again. For example, let s assume there is a java.util.List has a set of Objects. and then that list is written to a text file. Then later that file will be read again and get all objects from list and then change one object's value at run time by a java application. Then I don't need to write entire list back to the text file. Instead only the updated object in the list is required to be rewritten or updated in the text file without rewriting the whole list again. Any suggestion, or helpful source with sample codes please.
Take a look at RandomAccessFile. This will let you seek to the place in the file you want, and only update the part that you want to update.
Also take a look at this question on stackoverflow.
Without some fairly complex logic, you won't usually be able to update an object without rewriting the entire file. For example, if one of the objects on your list contains a string "shortstring", and you need to update it with string "muchmuchlongerstring", there will be no space in the file for the longer string without rewriting all the following content in the file.
If you want to persist large object trees to a file and still have the ability to update them, your code will be less buggy and life will be simplified by using one of the many file-based DBs out there, like:
SQLite (see Java and SQLite)
Derby
H2 (disk-based tables)
I am currently writing a program which takes user input and creates rows of a comma delimited .csv file. I am in need of a way to save this data in a way in which users are not able to easily edit this data. It does not need to be super secure, just enough so that it couldn't accidentally be edited. I also need another file (or the same file?) created to then be easily accessible (in the file system) by the user so that they may then email this file to a system admin who can then open the .csv file. I could provide this second person with a conversion program if necessary.
The file I save data in and the file to be sent can be two different files if there are any advantages to this. I was currently considering just using a file with a weird file extension, but saving it as a text file so that the user will only be able to open it if they know to try that. The other option being some sort of encryption, but I'm not sure if this is necessary and even if it was where I would start.
Thanks for the help :)
Edit: This file is meant to store the actual data being entered. Currently the data is being gathered on paper forms which are then sent to the admin to manually enter all of the data. This little app is meant to have someone else enter the data from the paper form and then tell them if they've entered it all correctly. After they've entered it all they then need to send the data to the admin. It would be preferable if the sending was handled automatically, but this app needs to be very simple and low budget and I don't want an internet connection to be a requirement.
You could store your data in a serializable object and save that. It would resist casual editing and be very simple to read and write from your app. This page should get you started: http://java.sun.com/developer/technicalArticles/Programming/serialization/
From your question, I am guessing that the uneditable file's purpose is to store some kind of system config and you don't want it to get messed up easily. From your own suggestions, it seems that even knowing that the file has been edited would help you, since you can then avoid using it. If that is the case, then you can use simple checks, such as save the total number of characters in the line as the first or last comma delimited value. Then, before you use the file, you just run a small validation code on it to verify that the file is indeed unaltered.
Another approach may just be to use a ZIP (file) of a "plain text format" (CSV, XML, other serialization method, etc) and, optionally, utilize a well-known (to you) password.
This approach could be used with other stream/package types: the idea behind using a ZIP (as opposed to an object serializer directly) is so that one can open/inspect/modify said data/file(s) easily without special program support. This may or may not be a benefit and using a password may or may not even be required, see below.
Some advantages of using a ZIP (or CAB):
The ability for multiple resources (aids in extensibility)
The ability to save the actual data in a "text format" (XML, perhaps)
Maintain competitive file-sizes for "common data"
Re-use existing tooling support (also get checksum validation for free!)
Additionally, using a non-ZIP file extension will prevent most users from casually associating the file (a similar approach to what is presented in the original post, but subtly different because the ZIP format itself is not "plain text") with the ZIP format and being able to open it. A number of modern Microsoft formats utilize the fact that the file-extension plays an important role and use CAB (and sometimes ZIP) formats as the container format for the document. That is, an ".XSN" or ".WSP" or ".gadget" file can be opened with a tool like 7-zip, but are generally only done so by developers who are "in the know". Also, just consider ".WAR" and ".JAR" files as other examples of this approach, since this is Java we're in.
Traditional ZIP passwords are not secure, and more-so is using a static password embedded in the program. However, if this is just a deterrent (e.g. not for "security") then those issues are not important. Coupled with an "un-associated" file-type/extension, I believe this offers the protection asked for in the question while remaining flexible. It may be possible to entirely drop the password usage and still prevent "accidental modifications" just by using a ZIP (or other) container format, depending upon requirement/desires.
Happy coding.
Can you set file permissions to make it read-only?
Other than doing a binary output file, the file system that Windows runs (I know for sure it works from XP through x64 Windows 7) has a little trick that you can use to hide data from anyone simply perusing through your files:
Append your output and input files with a colon and then an arbitrary value, eg if your filename is "data.csv", make it instead "data.csv:42". Any existing or non-existing file can be appended to to access a whole hidden area (and every file for every value after the colon is distinct, so "data.csv:42" != "data.csv:carrots" != "second.csv:carrots").
If this file doesn't exist, it will be created and initialized to have 0 bytes of data with it. If you open up the file in Notepad you will indeed see that it holds exactly the data it held before writing to the :42 file, no more, no less, but in reality subsequent data read from this "data.csv:42" file will persist. This makes it a perfect place to hide data from any annoying user!
Caveats: If you delete "data.csv", all associated hidden data will be deleted too. Also, there are indeed programs that will find these files, but if your user goes through all that trouble to manually edit some csv file, I say let them.
I also have no idea if this will work on other platforms, I've never thought to try it.