Thursday, February 2, 2017

Java Tutorial : How To Save And Load Data In Java (Codes and Example)


In This tutorial, I'll show you with example how to save and load data in java using .txt file and how to add these data to list or array for using them in your program or game.


1. How do save and load work?!
Let's say you are playing a shooting game like Call of Duty. Your Health is 100 by default when you start the game, while playing the enemy shoots you, your Health will decrease to be 70, now you don't want to play, you will save the game at this status and close it so you can continue playing later. let's see how this process goes as we will do.

Saving process:

Start the game >>  variable health is 100 by default >> while playing you gets shot >> variable health is 70 >> you hit save button >> the program wrote  (save.txt) file containing the value of Heath 70 >> you close the game.

Loading process:

Start the game again  >> you hit load button >> the program reads (save.txt) file and changes the Health value to be 70 instead of 100 by default  >> you continue playing form the last status you save with Health is 70.

2. Let's write our code for saving (writing a file).

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class SaveAndLoad {
   static int Health = 100;
    /**
     * @param args the command line arguments
     */

  public static void main(String[] args)  {
     
         //Health changed to be 70 after the enemy shot you.
         
           Health = 70;
         
       try {
       
          //You clicked the save button the program will save Health to txt file.
          PrintWriter Saver = new PrintWriter ("save.txt", "UTF-8");
       
          //writing Health = 70 in the file. 
          Saver.println(Health);
       
          //close the save.txt file after writing.
          Saver.close();
         
     
       } catch (FileNotFoundException ex) {
           Logger.getLogger(SaveAndLoad.class.getName()).log(Level.SEVERE, null, ex);
       } catch (UnsupportedEncodingException ex) {
           Logger.getLogger(SaveAndLoad.class.getName()).log(Level.SEVERE, null, ex);

       }
    }

}

Notes:
1. Save.txt will be written in the same project folder (\NetBeansProjects\SaveAndLoad), I'm using netbeans!
2. You can add path for save.txt file ( PrintWriter Saver = new PrintWriter ("D:\\test\\save.txt", "UTF-8");)
3.You can save more variables, example:
  int Health = 70, int Stage = 3, int Money = 5000

 Saver.println(Health);
 Saver.println(Stage);
 Saver.println(Money);

When you open save.txt you'll see:

70
3
5000

It's very important to save them in order so you can load them easily.

3. Let write our code for loading (reading a file):

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;


public class SaveAndLoad {
 
  static int Health = 100;
   static int Stage = 1;
   static int Money = 1000;
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)  {
     
      try {
        //loading the file. 
     
FileInputStream fstream = new FileInputStream("save.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
     
        //creating a list for adding the save.txt data. 
java.util.ArrayList<String> list = new java.util.ArrayList<String>();
     
        //Reading and adding to the list.
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
   //creating an array and adding the data to it.
  String [] stringarr = list.toArray(new String[0]);

        //printing the list to make sure every thing is okay.
System.out.println( "the first line is: " + list.get( 0 ) );
        System.out.println( "the Second line is: " + list.get( 1 ) );
System.out.println( "the third line is: " + list.get( 2 ) );
     
        //printing the array to make sure every thing is okay.
        System.out.println( "array 1: " + stringarr[0] );
        System.out.println( "array 2: " + stringarr[1] );
        System.out.println( "array 3: " + stringarr[2] );
       
        // change the value to the last saved game status .
        // varialbe = list.get();  or  varialbe = stringarr[];
     
        Health =Integer.parseInt(list.get( 0 ));
        Stage =Integer.parseInt(list.get( 1 ));
        Money =Integer.parseInt(list.get( 2 ));
       
        //printing the variables to make sure every thing is okay.
        System.out.println( "Health: " + Health );
        System.out.println( "Stage: " + Stage );
        System.out.println( "Money: " + Money );

 //close the save.txt file
in.close();
}
     
     
catch(Exception e) {    
System.err.println("Error: " + e.getMessage());
}
       
           }

       }

 Notes:
1.Save.txt file contents:

70
3
5000

2. When you run the code the output will be:


the first line is: 70
the Second line is: 3
the third line is: 5000
array 1: 70
array 2: 3
array 3: 5000
Health: 70
Stage: 3
Money: 5000

That's everything for this tutorial I hope, I could help. 


No comments:

Post a Comment