Saves game level settings - java

I have been coding for about a month and I have found ways to adapt around ever problem but one. The problem as you can probably see by the title is how to make a way to make game saves. I am currently creating a very simple game that has about 5 classes of my code and maybe 2 of Java Swing GUI.
I know how I would like to go about the saving process but I have no idea how to do it in my code. How I would like to go about doing this is by making the code print a Number or Integer to a file to represent a Level. For example if you completed level 1 the number in the file would be 1. I have tried some templates for this but none of them work.
I understand how to write to a file but my problem is reading it from a jar or even creating a file then reading it from a place on the computer. I need to know how to find a file URL for different computers because some use Docs and Settings and other Users. Please could someone help.

Since the jar is read only, it can only contain the 'default settings'. See this answer for the general strategy to deal with such a embedded-resource.
Speaking of which (embedded resources) see the info. page for more details on how to access them.
Here is an example of storing and reading a Properties file from the 'current directory'.
As mentioned by #MadProgrammer though, it is safest to put the settings file into a (sub-directory) of user.home, as seen in this answer.
But a properties file is just one option. You might also serialize an object, or write the file in a custom format that your app. knows how to read, for the first two off the top of my head.
Besides 'serialize (in some form) in a File', there is also the Preferences API, or for desktop applications launched using Java Web Start, the PersistenceService. Here is a demo. of the service.

I need to know how to find a file url for different computers because
some use Docs and Settings and other Users
The System property user.home points to the user's home directory
File userHome = new File(System.getProperty("user.home"));

Related

Where should I place a file when the path is "./"?

I am maintaining a Spring Boot project. There is this code:
BufferedReader reader = new BufferedReader(new FileReader("./setting_mail_sender.txt"));
Where should the file be located in this case?
In 'the current working directory'. And where is that? Who knows!
Whomever wrote that code messed up. It's not a good idea to use the CWD for anything in any java code unless you specifically know you want it. And generally, that's only the case when you're writing command line tools in the vein of the various tools you find in your average linux distro's /bin dir - a rare occurrence, given that the JVM isn't really designed for that kind of thing.
There are 3 different best practices for 'data files' depending on the nature of the data:
Static, unchanging data - as much part of your app as your class files are. These should be loaded with MyClass.class.getResource("name-of-resource.txt") and shipped the same way your classes are. For example, inside the jar file.
Config files. These should usually be in System.getProperty("user.home") - the user's home dir; /Users/yourusername on macs, /home/yourusername on linux, C:\Users\YourUserName on windows. Best practice is to ship a 'template' version of the settings file if relevant in the jar file, and upon detecting that there is no config file present at all, to write out the template (and you load the template in via MyClass.class.getResource). If a template is not a good idea, something in a similar vein. Bad practice is to have the installer do this, and have your app be broken or leave the user having to peruse complex documentation to (re)create the config file. A different way to do it right is to have a config page in your app (a window, menu bar setting, web app thing - something with a user interface) where you can change settings and the config file is simply the way you store that data.
Changing data files. For example, you ship H2 (an all-java database engine) with your app and it needs to write its database file somewhere. This is a bit tricky; user home is not the right place for such data files, but you can't really 'find' the dir where your app is installed either. Even if you can, on non-badly-designed OSes, apps usually cannot (and should not!) be able to write to that location anyway. The location where this data is stored should definitely be configurable, so one easy way out is to require that the user explicitly picks a place. Otherwise I'm afraid you're stuck having to write per-OS code - find /Users/myusername/Library/Application Support/yourappname on mac, which is the right place. As far as I know there is no library to do this right.
None of them involve 'require that the user start the app with the right CWD'. There are good reasons for that: It can be hard to configure, and it's not something users think of to configure. For example, when setting up a java app as a recurring task in windows, you can configure the working dir for such a process, but it's not something that's usually considered as crucial configuration. When running a java app from the command line, who knows what the working dir is. You'll end up with an app that usually works, except in some circumstances when it magically doesn't, and most of your users have no idea that the difference between the magic run that works and the one that does not, is the directory they were in when they started the java app.
If you can edit that code, do so - figure out which of the 3 different kinds of data this is about (sounds like the second bullet: Config stuff, so should be in user home, and the app's name should be part of the file name) - and fix it. for example, that should be:
try (var in = Files.newBufferedReader(Paths.get(System.getProperty("user.home"), "myapp-mail.conf")) {
}
This solves a whole bunch of problems:
Uses try-with to avoid resource leakage.
Reads from user.home, avoiding current working directory as relevant setting.
Actually uses UTF-8 encoding (whereas your code will, at least until java 17, do 'platform default'. It's somewhat unlikely you want that, as it means your config file is not portable; copying it from one computer to another may break things. You presumably don't want this.
If errors occur, the error messages are improved (one of the downsides of the 'old' file API).
If you can't change this code, figure out what the CWD is; put the files there, and ensure that, however you start this spring boot project, you always start it from that directory. If you can't change this code but you can run some code in that JVM, you can print it: System.out.println(Paths.get(".").toAbsolutePath()) will show it to you.

Publish updatable Java software through Wordpress

I have just written a Java program that I now need to publish. I want to make the software easily updatable, and I therefore need your advice. The program will be used by people with minimal technical knowledge, hence usability is absolute key. The program is not open source.
The situation is this:
First time users download a zip-file containing one .jar-file and two folders that should contain the program output files (.xml-files and .png-files). I want to make it as easy as possible for the user to update the .jar (replace it with another .jar, not necessarily at run time). To my help I have a simple web-based Wordpress site that the user will view as the source of the program.
I'll list the possible solutions I've come up with:
1 (fallback solution). The user have to manually go to the Wordpress site where I'll put a separate direct download link (from Google Drive) for the .jar-file. The user then has to manually replace the .jar in the existing folder with the new one.The drawback to this is that it requires too much work from the user, and they program probably won't get updated very often.
2. Alongside the Program.jar in the zip-file the first user downloads, I place another Program-Updater.jar. This new .jar's sole purpose is to, when the user opens it, download a new version of Program.jar from the web and replace the existing one.This is better than the previous option because it requires less work, even though it's not automatic. The drawback is that I need one more .jar which can confuse the user, and most importantly I have no way of updating the Program-Updater.jar.
3. Java Web Start.I've tried reading up on how this works, but I'm wondering if there is a way to get it to work. One possible problem is that I can't really access the host, and to be able to set up the .jnlp the correct way I think you need this. I'm also wondering how the program's file structure would be (is the .jar even placed on the user's computer?) and if this could confuse the user. Also how to make it always work offline.
4. Suggest your own solution!
Any input on this matter would be greatly appreciated, and I'll gladly give more info than I already have.
Cheers
Getdown was the way to go; it is extremely easy to use.
I'll put the .zip on Google Drive with a direct download link to it on my Wordpress site.
The files used by getdown are placed in and downloaded from my public git repo.

How to store high score inside a jar file

I am developing a small game in Java and I am shipping it as a single Jar file. I want to store the high scores/best times for that game somewhere. Instead of storing it in a separate file, I would like to store it in the application itself (inside the Jar) so that its not lost. Is this possible at all ? If so, how to do it programatically.
Java does not give you tools to modify the JARs which are currently run. If you really want to do it, you have to guess the location of the JAR by yourself (which might reside on a read-only filesystem) and modify it the same way you would modify any archive file.
Bottom line: it's a very bad idea, don't do it! See this question for a much more reasonable solution.
Nothing is impossible, but storing it in the jar file would make it very complicated. You might also end up with unwanted side effects like "Permission Denied" errors when the jar is owned by another user. Virus scanners might get nervous when they see jar files change without reason, etc....
I would look to the Preferences API for storing this kind of info.
I think it is a bad idea to try and store anything in the jar file. Another option is to have a web based service offered to the people playing with your game. The game could connect through a web service to your hosted server and then store everything centrally there. Not sure if it is exactly what you want but it's just an idea. It would also allow people to compete with each other.
Java JAR file is a ZIP-Archive, so you could possibly access it with standard ZIP-Tools and just extract one hisghscores.txt file, modify it and then pack it back again.

Holding Information in Android App

I've only just started to write in Java on Android, so please bear with me.
I have some settings I want to hold in my app, normally I would have used an xml file. Trouble is i'm not sure how to load it into the xml parser to read it.
I thought I might be able to drop it into /res/values/Info.xml and open it from there but it does'nt find the file.
I have also read that people are starting to use a SQLite database to hold information in, is this more the standard way to go?
thanks a lot
Luke
It sounds like what you want are Shared Preferences. Its a simple way of storing key value pairs, along with a UI for letting the user change them.
You could try storing to External Files (that way they can save settings on an SD card if they have 2.2). You wouldn't be able to modify the files in the res folder like you tried because these files get compiled into the app package. You could also try Internal Files found on the same page. SQLite might be a bit much for config settings.

Java - How to find that the user has changed the configuration file?

I am developing a Java Desktop Application. This app needs a configuration to be started. For this, I want to supply a defaultConfig.properties or defaultConfig.xml file with the application so that If user doesn't select any configuration, then the application will start with the help of defaultConfig file.
But I am afraid of my application crash if the user accidentally edit the defaultConfig file. So Is there any mechanism through which I can check before the start of the application that whether the config file has changed or not.
How other applications (out in the market) deal with this type of situation in which their application depends on a configuration file?
If the user edited the config file accidentally or intentionally, then the application won't run in future unless he re-installs the application.
I agree with David in that using a MD5 hash is a good and simple way to accomplish what you want.
Basically you would use the MD5 hashing code provided by the JDK (or somewhere else) to generate a hash-code based on the default data in Config.xml, and save that hash-code to a file (or hardcode it into the function that does the checking). Then each time your application starts load the hash-code that you saved to the file, and then load the Config.xml file and again generate a hash-code from it, compare the saved hash-code to the one generated from the loaded config file, if they are the same then the data has not changed, if they are different, then the data has been modified.
However as others are suggesting if the file should not be editable by the user then you should consider storing the configuration in a manner that the user can not easily edit. The easiest thing I can think of would be to wrap the Output Stream that you are using to write the Config.xml file in a GZIP Output Stream. Not only will this make it difficult for the user to edit the configuration file, but it will also cause the Config.xml file to take up less space.
I am not at all sure that this is a good approach but if you want to go ahead with this you can compute a hash of the configuration file (say md5) and recompute and compare every time the app starts.
Come to think of it, if the user is forbidden to edit a file why expose it? Stick it in a jar file for example, far away from the user's eyes.
If the default configuration is not supposed to be edited, perhaps you don't really want to store it in a file in the first place? Could you not store the default values of the configuration in the code directly?
Remove write permissions for the file. This way the user gets a warning before trying to change the file.
Add a hash or checksum and verify this before loading file
For added security, you can replace the simple hash with a cryptographic signature.
From I have found online so far there seems to be different approaches code wise. none appear to be a 100 hundred percent fix, ex:
The DirectoryWatcher implements
AbstractResourceWatcher to monitor a
specified directory.
Code found here twit88.com develop-a-java-file-watcher
one problem encountered was If I copy
a large file from a remote network
source to the local directory being
monitored, that file will still show
up in the directory listing, but
before the network copy has completed.
If I try to do almost anything non
trivial to the file at that moment
like move it to another directory or
open it for writing, an exception will
be thrown because really the file is
not yet completely there and the OS
still has a write lock on it.
found on the same site, further below.
How the program works It accepts a ResourceListener class, which is FileListener. If a change is detected in the program a onAdd, onChange, or onDelete event will be thrown and passing the file to.
will keep searching for more solutions.

Categories

Resources