I've looked around for this for a while now and haven't really found anything conclusive.
I have a java project that I want to run (Desktop Application) and I wish, upon the first startup, for the user to enter a few values which will remain the values of the respective variables forever, i.e. when I re-run the jar file, the changed values will show instead of the initial packaged values.
I tried using xml to store the file within the jar and read and write to it, no success. So now I've opt to do this.
However if there's a simpler way, please enlighten me, this is one of the initial steps of a bigger project for me and I refuse to go on till I solve this.
You should not write inside the JAR. I suggest you store the values user entered somewhere in that user's directory (you can use System.getProperty("user.home") to get the path to user directory). Then you can check if the file in user directory exists - if yes, use it, if not, use the one from your JAR that contains defaults (or ask the user to enter the values).
If you have only a few values to store, not a large file, then Preferences is the solution designed for this.
Preferences prefs = Preferences.userRoot().node("/com/yourcompany/yourprogram");
int value = prefs.getInt("key", -1);
if(value == -1) {
prefs.put("value", Integer.parseInt(
JOptionPane.showInputDialog("Enter value:"));
prefs.flush();
}
Related
This question already has answers here:
Detect first time user in java app
(3 answers)
Closed 6 years ago.
I would like to pop up a window to select a file location when the user launch the software for the first time. I'm new to javafx and I looked for an answer on the web but no success...
Thanks in advance
I think I found it.
primaryStage.setOnShowing(event -> {
//Code here
});
It does action on first startup. I don't know if it's the best way to do it but that's how I did it. I already have a file with about 3 lines. I just added a 4th one with a random word and when the user launch the app it check if the word exist in the file. If so, it does nothing. If not, it ask the user to select the folder and if the selection is successful, it write the word.
Firstly, I would want to point out that your phrasing probably isn't clear enough for most people to understand exactly what you need. I am going to assume you have some kind of settings (like default application storage directory) which you need the user to specify at the first time the JAR is run. If the JAR file is run subsequently, it should not prompt for that again and use the settings previously specified.
Typically, when the user runs the JAR file, all the data would be isolated within that session. If the user closes the application and opens the application again, it would behave just like the previous run.
If you need to persist these data or settings, you can use Properties. This will save data in a separate file. The normal convention is to save it in the same folder as the JAR file, and named as config.properties.
At the start of the application, you should check if this file exists, if it does not exist, it means that this is the first run. Subsequently, when the user set the data (e.g. file folder), you would save it to the file.
You can find an example here.
Background
In order to implement a file selector, we can make use of JavaFX’s FileChooser. This will open a window giving us the opportunity to select a file.
What you’re asking for is for a FileChooser to open prior to entering the actual application. Let’s have a look at the implementation for something like that!
Implementation
At first, we’re going to need a JavaFX Application class that will open a window if we were to create a new instance out of it:
public class App extends Application
{
private final File file;
public App(File file)
{
this.file = file;
// Optionally provide ‘launch’ with some arguments
Application.launch();
}
#Override
public void start(final Stage stage)
{
// ...
stage.setScene(new Scene(insertNodeHere));
}
}
As I’m certain you’re already aware of—a class like this will open up a new window. This is the separate application class we’ll be calling once we’ve retrieved a File using the FileChooser in our main class.
In our main class, we’ll put this:
File file = fileChooser.showOpenDialog(stage);
if (file != null)
new App(file);
This will launch your application if the selected file didn’t turn out as null.
Moreover
With the implementation above in mind, you can complicate things as much as you feel like. Perhaps you’d like the application to start even if the file were null? In that case, there’s no need for the if statement.
I have a java program compiled as a .jar and it requires an activation key to be enabled. I want the jar to prompt you for the activation key on the first runtime and once its been activated, store a string which it could read during later runtimes to determine if it had been enabled.
Any suggestions on how to go about this?
Note: I want the string to be stored secretly so someone couldn't trick the program into thinking its been enabled.
Update: I've been toying with the preferences api and am using this code to store if the program has been enabled:
String key = "userKey";
String saveString = "enabled";
Preferences root = Preferences.userRoot();
root.put(key, saveString);
And this to get if during a later runtime:
String key = "userKey";
String failedtoLoad="Program not enabled";
Preferences root = Preferences.userRoot();
String status=root.get(key, failedToLoad);
Everytime I run the program status ends up being failedtoLoad and the saveString isn't found, unless I save the string and get the string in the same runtime. Why is this?
Have a look at the Java Preferences API (http://docs.oracle.com/javase/8/docs/technotes/guides/preferences/index.html). It allows to store preferences and configuration data between executions of your program.
About the secrecy: As JDong already mentioned, if your program must be able to read it, it's very likely that somebody else can also read it, it's in the end just a question of how difficult you want to make it to them. Best is to have some String that your program can algorithmically verify to decide whether it is a valid key or not. In that case, somebody else could still search for the installed key and reuse it somewhere else, but that's just like if the first person passed the key along to some other user.
If you actually want security, you would have to work harder at obfuscation than any potential attacker would work at reverse engineering. Look at implementations of successful DRM if you want to know how to implement security at the code level. These usually involve multiple non-obvious checks in the code with some server that verifies the key.
An alternative I prefer is to have the user agree to some legalese that limits their usage.
Currently my application using this path for taking images:
D:\Workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\webapps\patternImages
So inside of this folder might be n number of folders may contains n number folders and inside of the folders it may contain n number of images,
I need to get all the image names.
In this case there are 2 scenario we go for usually getting image path
Using the static string path to get the image names
Using system.getproperty()
But I need more dynamic way of approach:
By this "patternImages" folder can be placed anywhere in the web and I should have to get all the folders name and image names without any issue and also should know which folder contains which image? any way?
It's hard to say what would be a perfect fit for your application since we don't know everything you're doing, but since it's a GUI application, I imagine presenting the user with a GUI to pick the file path is your best option. What class you use for that depends on what GUI library you're using, but here's a tutorial for JFileChooser: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html. The basic code you need is this:
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
} else {
// Do nothing or log it
}
where fc is an instance of JFileChooser. Just make sure you configure the object for picking directories and not files. You would probably wire this up to a button. Whatever library you use should provide some kind of dialog element to allow the user to pick a directory.
If a graphical directory picker is not an option, then I think you're stuck with a configuration file. Even if you can use a directory picker, you might want to consider a configuration file to save the user's last choice.
I built a camera app. My problem is that I want to continue the logical naming the default camera app uses.
EG: The camera app produces files such as:
IMG_20130104_033852
IMG_20130104_033853
If these are the only contents of my /camera folder, I should theoretically name my photo IMG_20130104_033854. Should I look for the image with the "biggest" name and add a number or is there a better solution for this problem?
I would suggest building the name up until the point you get to the last sequence of numbers, and then you could look for the biggest number and add one to it if you feel like it.
So for instance, based off of today's date, you could build the IMG_20130121_ part. You could do File [] fList = f.listFiles();, where f is pointing to the /camera/ directory. From there, you could check the files by doing fileName.startsWith("IMG_20130121_") in an IF statement.
From there, do a substring to grab the string-numbers after the last underscore (_), convert to Integer, and loop through until you finish comparing all the Integers.
I did this for folder names. A standalone cd burning device creates folders that start with ezb_, followed by a number. I can paste my looping code tomorrow if this info wasn't enough.
As a sidenote, if you were to start your own naming algorithm after IMG_20130121_, like adding an s or something, you'd still have to either keep track or look for the biggest number. You might as well just implement something like what I tried to explain. Let me know if I need to clarify!
I have to develop a small app to compare automatically generated folders. It must compare the folders, sub-folders and file contents. The problem is that this app needs to be launched either from a user on his computer to manually check for changes, or automatically along with the ANT nightlies. In the first case the results are displayed as a table in the Swing GUI. But in the other case, it must create a file to put the results in (format doesn't matter, XML, CSV, ...).
Anyone got some tips, or a link to a tutorial ?
You might want to add some command line option that switches between ui and file export, e.g. --gui or --export=[filename]. You could use Apache Commons CLI for that.
The other method is to create a set of classes that performs the task, and returns a set of values, which can then be either written to disk, or displayed in a GUI. I.e., an engine, and two front-ends (the GUI and the CLI).
for example:
public interface DirectoryComparer {
CompareResult performCompare(Directory dir1, Directory dir2);
public static interface CompareResult {
//...things here that you need, such as, file or dir difference, etc
Iterable<File> getFileDiff();
Iterable<Directory> getDirectoryDiff();
}
}
then, the GUI clients will just use DirectoryComparer to display the results, and the CLI client will write these results to a file or three. But those two clients are completely separate, and can be maintained separately.