Methods of storing permanent data in java

23.1k views Asked by At

I am currently doing a programming assignment and it says that we should "store all the data in a data file and need to check the compatibility of the user PIN and account no. validity"

Unfortunately my lecturer has not taught us about data files, and when I googled I found two different answers,

  1. Store data in notepad (.txt) file
  2. Store data in csv file

MY QUESTION IS WHICH ONE IS A DATA FILE? and how do you retrieve the user PIN (after its typed from buffer reader) to check whether both are correct? Any Help is GREATLY APPRECIATED!!

4

There are 4 answers

0
Kristof Mols On BEST ANSWER

from wikipedia:

A data file is a computer file which stores data for use by a computer application or system.

So both a *.txt file and a *.csv file are data files.

A *.csv (comma-seperated values) file is in essence a *.txt file that separates your values by a ,

The 2 methods you found should do about the same, but it will be easier to use the csv-method.

0
Hendra Jaya On

It doesn't matter whether it's txt or csv. You can even save it in xml. Don't get confused with file extension. The only thing you should care about is "how you can save/load those data".

  1. To save in .txt is fine but perhaps you will need to define your own 'formatting' just to make sure that you can load that data.
  2. If you save it in .csv is also nice since you don't have to invent your own 'formatting'. Just follow several legacy format like delimiter, encloser etc.
  3. To save in another format is also good. For example, XML. But, again, you need to follow a legacy formatting in XML like DTD.

Good luck

4
Andreas Dolk On

The easiest way is using the Properties class. It stores key/value pairs and can persist the data to a properties files. Here's a working example:

Properties p = new Properties();
p.setProperty("johndoe.pin", "12345");
p.store(new FileWriter("myfile.properties", "");

and reading:

Properties p = new Properties();
p.load(new FileReader("myfile.properties", "");

The check will be done with the properties object:

public boolean isValid(String user, String pin) {
  return pin.equals(p.getProperty(user + ".pin"));
}

It is easy but of course there's no encryption. The file is stored in plain text including the PINs.

1
jonescb On

Serialization is another method of persistent storage.
You can create a class that implements Serializable with a field for each piece of data you want to store. Then you can write the entire class out to a file, and you can read it back in later. I believe the Serializable interface outputs the class into some sort of binary/hex representation.

There are other ways to to do serialization without using the standard Java serialization, like you can use a JSON library.