Java "Save" vs "Save As" Strategies - java

I am building a basic paint application and have implemented Open and Save functionality, however, I would like to add in "Save As." Essentially, Save As would always make use of JFileChooser, but Save would automatically write to file if a file already exists and is currently being edited.
With that said, what strategies can I invoke to streamline this process? Obviously, Save As is already complete per the implementation of the Save feature I have already written (I apologize if that wording is confusing). However, in order to make the "Save" feature function as I intend it to, I believe I would need a way to keep track of whether or not the file exists and is currently being edited.
So what is a good way to keep track of whether or not a file exists and is currently loaded--and if it is, the Save function will write without JFileChooser, but if it isn't, it will launch the Save As functionality.
For what its worth, the Save feature, as highlighted, should apply when the Open dialog is called, so I could keep track of this somehow. I am also Opening bufferedimages and laying them as TexturePaint over my shape objects. So when the above happens is when I want the Save dialog to work as a "normal" save function, so that is another feature to take into consideration.
However, I would really like to learn about some good strategies to accomplish this in a more generic sense. Thus far, I have come up empty handed.

You can add a field to the object that stores the file name, and it's only set when you Open a file, or when you use Save As. Then, if the file name is null, clicking on Save actually calls Save As's code instead.

Related

JFace - How to remove preference property?

I'm wokring with a little JFace preference store where I can add preferences straight forward enough, but have trouble when I want to remove one of the preferences I've put in.
I can't see anything in the APIs that allows for removal. What is the correct way for doing this?
Assuming you are using IPreferenceStore you call setToDefault("pref id") to reset a preference to its default value.
This is weird !!
I asked this same question 3 days ago in the eclipse JFace forum: https://www.eclipse.org/forums/index.php/t/1088245
I only got answers not related to my need.
The answer is that it is not possible. Also you can not set the value or the default of a preference to "null"
In my app (JMSToolBox), the need is to "cleanup" the file that is backing the PersistenceStore as the user may store a lot of "keys/preferences" that may become obsolete at some point in time. I wanted a way to "remove/delete" them from the file to keep the PreferenceStore file as compact as possible.
I ended up writing my own version of PreferenceStore that exposes the "remove" method from the internal "Properties" object used by PreferenceStore. This class is not designed to fullfill my need.
Code is here

ObjectOutputStream Advice

The goal with my program is to have it save when closed, and reloaded when opened.
I have a driver (which contains all of the graphics) and I want it to create and save a file. I've seen numerous tutorials on the internet, but what they fail to explain is how to correctly implement this system in an actual program.
Do I create the OutputStrema in my main method? Do I need to check if a file has been created and if not create one, and if so read from it? How do I accomplish all of this? Should I have a WindowListener for quitting so that it can save all of the data?
Thanks
Yes, a WindowListener sounds like a good idea. One way to save the state of a program is to use Properties. Please have a look at the tutorial linked to above. I'm not sure what to recommend for your "graphics". Please tell us more details about just what you mean here.
Edit
Do I create the OutputStrema in my main method?
you're question re creating the OutputStream in the main method is asking about program structure that we know nothing about. My gut tells me that i wouldn't create anything like this in the main method, even if the JFrame is created there (or in a static method called from main). The OutputStream would be created in the class that implements the WindowListener, and this can be its own stand alone class. You want to make the main method as small as possible.
Do I need to check if a file has been created and if not create one, and if so read from it?
Possibly. This question revolves around what you're going to do with the stored information once created. Perhaps you'll search for it and read it on program start up? I don't know as it all depends on your needs, something you'll have to figure out.
How do I accomplish all of this? Should I have a WindowListener for quitting so that it can save all of the data?
If this is a Swing application, then yes, a WindowListener would help you control your application's closing.
Do I create the OutputStrema in my main method?
It would be better to create the stream at the point where you are saving the state.
When my program runs it is going to take in the saved data file with its ObjectInputStream. Do I put the code to accomplish this in my Main method?
Sounds like a good choice. Basically, you need to do this before you attempt to do something that needs that data. Anything that achieves this will work (though doing it using static initialization is a bad idea ...)
Do I need to check if a file has been created and if not create one, and if so read from it?
This question is confusing writing the state file and reading it. They occur at different points in the lifecycle, and use different code to do the task.
There is no point checking to see if a save file exists before creating one ... unless you propose to rename the existing save file.
Conversely, if a save file doesn't exist when you start the application, then the constructor that attempts to open it will throw a FileNotFoundException. Just catch the exception and skip the code that reads the saved state.
... if there has not been a file created yet, will this cause an error?
Yes. A FileNotFoundException; see above. So your code has to deal with that, or test to see if the file exists before attempting to open in; see File.exists() and related methods.
Should I have a WindowListener for quitting so that it can save all of the data?
That sounds like part of the solution. (But what about the case where the program crashes or is killed? Do you want to save state in those cases ... or not?)
A couple of things to beware of:
Many GUI-related objects do not implement Serializable, and therefore cannot be saved using an ObjectOutputStream. Threads, streams, sockets and a few other things can't be serialized either.
When you save instances of classes using ObjectOutputStream, change the classes or their names, and then attempt to reload them using ObjectInputStream, you are liable to run into trouble with saved instances not matching the new versions of the classes. If you have to be able to read that serialized state you are in trouble.

Saving a game (Android app.)

This is somewhat of an open question.
I'm in the process of developing a simple game for android and I've gotten to the point where I'm trying to enable thee user to save their progress and return later.
As i'm a beginner, I'm not exactly sure where to start, so I was hoping some of you might have at least some suggestions.
A little info on the setup of the game:
All animation is done in a thread through a canvas and alternation of stored bitmap frames based on a 30 ms loop.
Everything is an object, the characters, the background is simply a 2d array of objects. and each object is generally referenced and created dynamically through a hashmap.
Now how to save? I know I could brute force it, and simply save coordinates and current actions blah blah etc. etc. for each object in each map.
But is there a better way to do this? I've briefly read that in python there's a method of sterilizing objects called "pickle," and there is something similar called "kryo." Am I looking in the right direction?
You should look into Java serialization. It's not perfect, it has problems, but it's the safest, quickest way to turn a complex tree of objects into something that you can save to a file or a db, and load it back when you need.
Else, there's always the possibility to use your own specific serialization using INSERT SQL queries, etc. But be very careful, it's easy to miss parts of what you want to save / restore. One example of that would be to turn your objects tree into XML and save that XML as a file. There are very good 3rd-party libs to map objects to XML and back in Java.
Well.. That's not STERILIZATION, but SERIALIZATION.. Which is a programming technique. And serialization is also the technique you want to use.
Doesn't matter if you use a predefined method or something you write on your own, but the only thing that matters is to loop across the objects and write to the file (or saving structure) the date you need to be later reloaded.
Anyway yes, you're looking the right way.
The best way to do it is implementing a serialization interface. Each object for which the serialize() method is called must save it's data and then call the serialize() method for each child object it owns.

Should I implement File Dialog as Singleton?

I'm developing a swing based application where I'm using many FileDialogs? So I say why not to make just one FileDialog object instead all of these instances and use it in the whole project? Is this a good assumption? does this have any performance improvement?
Thanks
This is a great example of a use case where application performance doesn't really matter and the question actually falls into the premature optimization class of problem solving. Why? Using FileDialog means that you are interacting with the user who, even if skilled beyond skilled with shortcut key Kung Fu, will be many orders of magnitude slower than the application. How many FileDialogs could a speedy user open, use and close in one minute? Say a dozen. You should not need to care about a dozen objects coming and going in one minute. Shouldn't even appear on your radar. Use your energies elsewhere. In fact, you should create a new object every time and avoid any caching headaches.
I would make a static FileDialog class that generates a new instance of the FileDialog each time a new one needs open rather than sharing a Singleton instance across the application.
That'll save you the headache of trying to figure out if you're reading the correct path from the dialog box or if somebody has opened the dialog and picked a new path and now you're referencing that new path rather than the originally selected path, etc...
Why implement is as a Singleton? Can you actually verify that displaying two file dialogs will never occur?
Better to have it as a regular class; you don't want to build in limitations which could become pain points later.
It isn't like your application is going to be critically overloaded by millions of calls to the file dialog, and who knows, perhaps someday it will be the right solution to have two file dialogs. Even if you don't display them both at the same time, perhaps holding the history in a "source" dialog and having a separate history in the "destination" dialog would be a blessing in a file transfer program.
Forget performance/speedyness. It doesn't matter here. Semantics matter. Reusing the same file dialog may give you things for free. Will the dialog start in the same directory every time? It will if it is the same instance. If you are creating new dialogs you will have to set startup dir your self.
Also why make it impossible to create more than one instance? Just make an instance member in your frame and be done with it.

Lock Properties File in Java

I am using the java properties file construct. At the beginning I read it to populate a dialog, but I also give the users the ability to change the values in the dialog and click save. This causes me to call the setProperty method of the properties file. Now, since this webapp can exist over multiple browsers, all changing the same file, I want to be able to "lock" the properties file whenever I am in the "save" method. How can I accomplish this? I've seen similar questions refering to FileLock, but I am unsure if this applies to the properties file construct. Is each "setProperty" a different write?
Thanks!
setProperty merely updates the set of properties, it does not write the file. You have to call the store(OutputStream out, String header) method to actually write out the file to disk, and that is the time where you'll have to "lock" the file.
You can use FileLock to prevent multiple users from writing to the file at the same time, however, each time your user wants to save, you will need to reload the property file from disk, change the property, and write the file back again, all without releasing the file lock, to make sure no stale data is saved.

Categories