define new variables and assign values by using text file - java

In shell script, I can use a loop to set new variables from a text file which contains variables and values. My text file looks like:
path1=/tmp/data
path2=/tmp/data2
myname=ABC
In java, is there any way to do like that?

Yes, it is possible and it is quite a common practice. Many server-based applications are designed in a way that they can fetch such variables from a file rather than a database.
These two links are all you'll need to get started:
https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html
https://docs.oracle.com/javase/tutorial/essential/environment/properties.html

Related

Is there a way to save the instance of a variable during debugging to reuse?

I am debugging something and I end up in a function that takes as parameters a keymap with many key-value pairs.
I would like to be able to reproduce this exact flow but I would be interested in re-using this exactly map (I mean the contents).
The map is populated by other parts of the program and going over the parts or somehow "copy/pasting" the values from the debugger is tedious. I thought there might be a standard solution to this.
Is there a way to somehow save the instance of the keymap and somehow create it in another program? Like serializing in a file I guess and reading in the file
Writting your keymap in a file is a solution. You can use JSON format to easily convert it.

Text file to string matrix java

I am making an auto chat client like Cleverbot for school. I have everything working, but I need a way to make a knowledge base of responses. I was going to make a matrix with all the responses that I need the bot to say, but I think it would be hard to edit the code every time I want to add a responses to the bot. This is the code that I have for the knowledge base matrix:
`String[][] Database={
{"hi","hello","howdy","hey"},//possible user input
{"hi","hello","hey"},//response
{"how are you", "how r u", "how r you", "how are u"},
{"good","doing well"}`
How would I make a matrix like this from a text file? Is there a better way than reading from a text file to deal with this?
You could...
Use a properties file
The properties file is something that can easily be read into (and stored from, but you're not interested in that) Java. The class java.util.Properties can make that easier, but it's fairly simple to load it and then you access it like a Map.
hello.input=hi,hello,howdy,hey
hello.output=hi,hello,hey
Note the matching formats there. This has its own set of problems and challenges to work with, but it lets you easily pull things in to and out of properties files.
Store it in JSON
Lots of things use JSON for a serialization format. And thus, there are lots of libraries that you can use to read and store from it. It would again make some things easier and have its own set of challenges.
{
"greeting":{
"input":["hi","hello","howdy","hey"],
"output":["hi","hello","hey"]
}
}
Something like that. And then again, you read this and store it into your data structures. You could store JSON in a number of places such as document databases (like couch) which would make for easy updates, changes, and access... given you're running that database.
Which brings us to...
Embedded databases
There are lots of databases that you can stick right in your application and access it like a database. Nice queries, proper relationships between objects. There are lots of advantages to using a database when you actually want a database rather than hobbling strings together and doing all the work yourself.
Custom serialization
You could create a class (instead of a 2d array) and then store the data in a class (in which it might be a 2d array, but that's an implementation detail). At this point, you could implement Serializable and write the writeObject and readObject methods and store the data somehow in a file which you could then read back into the object directly. If you have the administration ability of adding new things as part of this application (or another that uses the same class) you could forgo the human readable aspect of it and use the admin tool (that you write) to update the object.
Lots of others
This is just the tip of the iceberg. There are lots of ways to go about this.
P.S.
Please change the name of the variable from Database to something in lower case that better describes it such as input2output or the like. Upper case names are typically reserved for class names (unless its all upper case, in which case it's a final static field)
A common solution would be to dump the data in to a properties file, and then load it with the standard Properties.load(...) method.
Once you have your data like that, you can then access the data by a map-like interface.
You could find different ways of storing the data in the file like:
userinput=hi,hello,howdy,hey
response=hi,hello,hey
...
Then, when you read the file, you can split the values on the comma:
String[] expectHello = properties.getProperty("userinput").split(",");

JFrame saving user selections to a .txt file?

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();
}
});

Update objects written to a text files in java

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)

Best way to view/edit a property file in Java GUI?

I am trying to create a GUI tool to edit few property files, each property file contains large amount of lines. What's the best swing controls in Java should I use in order to load these property files.
Thanks,
You could present an editable JTable with two columns, one for property key, one for property value
http://zaval.org/products/jrc-editor/index.html
Take a look at this. It shows all keys in a tree like structure and let you edit them. Supports multiple locale dependent files and represent them accordingly.

Categories