-1

I have a program that reads and writes to a file. When I restart the program a few times, then the whole file is blank, so now the program won't start.

EDIT :

I have added the main class, to the post.

Code:

Game Class:

package gui;

import java.awt.AWTException;
import java.awt.event.KeyEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Game2 extends javax.swing.JFrame implements Runnable {
// Took out the menu items
/**
 * Creates new form Game
 */
public Game2() {
    initComponents();
}
// Class declarations
static final ShopExtras SE = new ShopExtras();
// Number values
static int clicks = 0 + read(0);
static int coins = 0 + read(1);

static int upgrade = 0 + read(2);

static int clicksToday = 0;
// Booleans
static boolean clickLoop = true;

public static void write() {

    Properties prop = new Properties();
    OutputStream writer = null;
    // Creates array copy of the values
    int[] data = new int[4];
    data[0] = clicks + 0;
    data[1] = upgrade + 0;
    data[2] = coins + 0;

    try {
        // Creates the file
        writer = new FileOutputStream("config.properties");
        // Adds the properties to the file
        prop.setProperty("clicks", "" + data[0]);
        prop.setProperty("upgrade", "" + data[1]);
        prop.setProperty("coins", "" + data[2]);
        prop.setProperty("click amount", "" + data[3]);

        prop.store(writer, null);

    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

public static int read(int i) {

    Properties prop = new Properties();
    InputStream reader = null;
    // Arrays for loading data
    int[] intData = new int[5];
    String[] data = new String[5];

    try {
        // Finds the file
        reader = new FileInputStream("config.properties");
        // Gets the file
        prop.load(reader);

        data[0] = prop.getProperty("clicks");
        data[1] = prop.getProperty("coins");
        data[2] = prop.getProperty("upgrade");
        data[4] = prop.getProperty("clicks today");
        // Prints out requested value
        System.out.println(prop.stringPropertyNames());
        // Gets requested value
        intData[i] = Integer.parseInt(data[i]) + 0;

    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // Returns requested value
    return intData[i] + 0;

}

public static void loopedTasks() {
    Thread t1 = new Thread() {
        @Override
        public void run() {
            while (true) {
                // First task
                label.setText("You have clicked: " + clicks + " times!");
                clickButton.setText("Click me! +" + 1);
                coinLabel.setText("You have: " + coins + " coins.");
                // Secondary Task
                write();
            }
        }
    };
    t1.start();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jMenu1 = new javax.swing.JMenu();
    jMenu4 = new javax.swing.JMenu();
    jMenu3 = new javax.swing.JMenu();
    jMenu6 = new javax.swing.JMenu();
    jPanel2 = new javax.swing.JPanel();
    resetButton = new javax.swing.JButton();
    clickButton = new javax.swing.JButton();
    label = new javax.swing.JLabel();
    coinLabel = new javax.swing.JLabel("You have: "+coins+" coins.");
    menuBar = new javax.swing.JMenuBar();
    shopMenu = new javax.swing.JMenu();
    clickerUpgrade = new javax.swing.JMenu();

    jMenu1.setText("jMenu1");

    jMenu4.setText("jMenu4");

    jMenu3.setText("jMenu3");

    jMenu6.setText("jMenu6");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

    resetButton.setText("Reset");
    resetButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            resetButtonActionPerformed(evt);
        }
    });

    clickButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            clickButtonActionPerformed(evt);
        }
    });

    label.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    label.setText("You have clicked: "+clicks+" times!");

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addComponent(resetButton)
            .addGap(0, 0, Short.MAX_VALUE))
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(coinLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                    .addGap(85, 85, 85)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(clickButton, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(label))
                    .addGap(35, 35, 35)))
            .addContainerGap(90, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
            .addComponent(coinLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(label)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
            .addComponent(clickButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(90, 90, 90)
            .addComponent(resetButton))
    );

    shopMenu.setText("Shop");

    clickerUpgrade.setText("Clicker Upgrade");

    shopMenu.add(clickerUpgrade);

    xPointsMenu.setText("Multiplied Points");

    shopMenu.add(xPointsMenu);

    menuBar.add(shopMenu);

    jMenu2.setText("jMenu2");

    menuBar.add(jMenu2);

    coinMenu.setText("Coins");

    menuBar.add(coinMenu);

    setJMenuBar(menuBar);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

    pack();
}// </editor-fold>                        

// Click and Reset
private void clickButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    clicks = clicks + 1;
    System.out.println(1);

}                                           

private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    clicks = 0;
    upgrade = 0;
}                                           


/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Game2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Game2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Game2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Game2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Game().setVisible(true);
            loopedTasks();
        }
    });
}

// Variables declaration - do not modify                     
public static javax.swing.JButton clickButton;
private javax.swing.JMenu clickerUpgrade;
private static javax.swing.JLabel coinLabel;
private javax.swing.JMenu coinMenu;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenu jMenu6;
private javax.swing.JPanel jPanel2;
public static javax.swing.JLabel label;
private javax.swing.JMenuBar menuBar;
private javax.swing.JButton resetButton;
private javax.swing.JMenu shopMenu;
private javax.swing.JMenu xPointsMenu;
// End of variables declaration                   

@Override
public void run() {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}

Write Method:

    Properties prop = new Properties();
    OutputStream writer = null;

    // Creates array
    int[] data = new int[1];
    data[0] = 10;

    try {
        // Creates the file
        writer = new FileOutputStream("config.properties");

        // Adds properties to the file
        prop.setProperty("integer", "" + data[0]);

        prop.store(writer, null);

        ...

Read Method:

    Properties prop = new Properties();
    InputStream reader = null;

    // Arrays for loading data
    String[] data = new String[1];

    try {
        // Finds the file
        reader = new FileInputStream("config.properties");

        // Gets the file
        prop.load(reader);

        // Gets the property
        data[0] = prop.getProperty("integer");

    ...

Error: java.lang.ExceptionInInitializerError Caused by: java.lang.NumberFormatException: null

Fix: Delete the config file. And run the program again.

Any help is very much appreciated!

StarCoder
  • 251
  • 1
  • 3
  • 16

1 Answers1

4

In this line: prop.setProperty("integer", "" + data[0]); you have set the propertie key to "integer".

But when you get that property, you are trying to get it using another key "clicks".

So the value of the data[0] in read method is null. Which is this error message trying to convince you:

Error: java.lang.ExceptionInInitializerError 
Caused by: java.lang.NumberFormatException: null

As a solution, change the key to:

data[0] = prop.getProperty("integer");

About getProperty() in doc:

public String getProperty(String key)

Searches for the property with the specified key in this property list. If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns null if the property is not found.

Parameters: key - the property key.

Returns: the value in this property list with the specified key value.

You can read doc to get some idea about Properties.

UPDATE:

Comment: Sorry, forgot to change that in my post. The whole file becomes null/blank.

First of all I have to say that your complete code not compilable(I had to do lot of things to come to this).

I think this is the steps that you got(after restart few times):

enter image description here

Reason for ExceptionInInitializerError:

Your read() is static and clicks also static, if static context goes wrong you will encounter this error message. read more.

Let's see what happened(step by step):

In this line: data[0] = clicks + 0; you trying to access clicks variable.

And that variable is calling to read(0): static int clicks = 0 + read(0);

Next, inside the read(), you are trying to do this:

intData[i] = Integer.parseInt(data[i]) + 0;//i is 0

Then, when trying to pass data[i] to integer, its null(thats what error message says).

Reason for java.lang.NumberFormatException:

cannot convert null values(empty string "") as integers. read more

You can handle this exception like below:

try{
    intData[i] = Integer.parseInt(data[i]) + 0;
}catch(NumberFormatException e){
    System.out.println("its null");//anything you want
}

This will handle the exception but your file clicks will reset to 0(file blank after few restarts).

Why its null?

When you run the program for the first time, you can see java.io.FileNotFoundException: but you program runs fine and after you clicks the button few times config.properties file is created.

The reason is, you havent call to write() before call the read().

As a solution check if properties file is exist before trying to read the file(config.properties).

Why this error occur after few restarts:

Because you are calling the method write() inside the loopedTasks() and its in a thread. Also you are calling this loopedTasks() inside the main thread. And these two method and other fields(including clicks) are static.

side note: you are messing with a static alot.

Read this, Java: when to use static methods? and watch this.

There multiple ways you can get this to work. However avoid using static(if you do not know use it properly, unexpected things will happen) and inside the main() do like this:

Game2 g= new Game2();
g.setVisible(true);
g.loopedTasks();

Lastly, I think you understood me.

Blasanka
  • 21,001
  • 12
  • 102
  • 104
  • Sorry, forgot to change that in my post. The whole file becomes `null`/blank. – StarCoder Aug 12 '17 at 20:00
  • @StarCoder have a look at now I have updated my answer – Blasanka Aug 13 '17 at 08:40
  • Thank you! I will try to do that, also thanks for the links! Reading them now! – StarCoder Aug 13 '17 at 20:26
  • Okay, so if I call `write()` before `read()` won't it just overwrite the file? – StarCoder Aug 13 '17 at 20:57
  • @StarCoder no thats happen because of `static`, before doing anything remove `static` and access through the instance in the main method. Then look what happen(its worked for me) – Blasanka Aug 14 '17 at 05:46
  • The reason Im saying to avoid `static` is that `static` variable shared common memory and concurrent access to that memory can crash your prog. Read last part of this answer also, https://stackoverflow.com/questions/12492969/static-variables-good-or-bad/12493079#12493079 – Blasanka Aug 14 '17 at 11:25
  • Okay, thank you for the help! – StarCoder Aug 16 '17 at 21:10