FileOutputStream随机写入null

时间:2017-08-12 19:09:18

标签: java swing file

我有一个 读取 的程序到文件中。当我重新启动程序几次,然后整个文件空白,所以现在程序将无法启动。

编辑:

我已将主要课程添加到帖子中。

代码:

游戏类:

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.
}

}

写入方法:

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

        ...

阅读方法:

    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");

    ...

错误: java.lang.ExceptionInInitializerError Caused by: java.lang.NumberFormatException: null

修正: 删除config文件。然后再次运行程序。

任何帮助都非常赞赏

1 个答案:

答案 0 :(得分:3)

在此行中:prop.setProperty("integer", "" + data[0]);您已将属性键设置为"integer"

但是当你获得该属性时,你正试图使用​​另一个密钥"clicks"来获取它。

因此,read方法中data[0]的值为null。试图说服你的错误信息是什么:

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

作为解决方案,请将密钥更改为:

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

关于doc中的getProperty()

  

public String getProperty(String key)

     

在此属性中搜索具有指定键的属性   名单。如果在此属性列表中找不到该键,则为默认值   然后检查属性列表及其递归的默认值。该   如果找不到该属性,则返回null

     

参数:       key - 属性键。

     

返回:       具有指定键值的此属性列表中的值。

您可以阅读doc to get some idea about Properties.

<强>更新

  

评论:对不起,忘了在我的帖子中更改它。整个文件   变为空/空白。

首先,我必须说你的完整代码不可编辑(我必须做很多事情来实现这个)。

我认为这是您获得的步骤(重启几次后):

enter image description here

ExceptionInInitializerError的原因:

您的read()是静态的,clicks也是static,如果static上下文出错,您将会遇到此错误消息。 read more

让我们看看发生了什么(一步一步):

在此行中:data[0] = clicks + 0;您尝试访问clicks变量。

该变量正在调用read(0)static int clicks = 0 + read(0);

接下来,在read()内,您正尝试这样做:

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

然后,当试图将data[i]传递给整数时,它的null(这就是错误信息所说的)。

java.lang.NumberFormatException的原因:

不能将空值(空字符串"")转换为整数。 read more

您可以像下面这样处理此异常:

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

这将处理异常,但您的文件clicks将重置为0(重启几次后文件为空白)。

为什么是null

首次运行程序时,您可以看到java.io.FileNotFoundException:,但程序运行正常,单击按钮后几次创建config.properties文件。

原因是,在致电write()之前,您尚未致电read()

作为解决方案,在尝试读取文件(config.properties)之前检查属性文件是否存在。

为什么在重启几次后会出现此错误:

因为您在write()中调用方法loopedTasks()并在线程中调用它。你也在主线程中调用这个loopedTasks()。这两个方法和其他字段(包括clicks)都是static

旁注:你正在弄乱static很多。

阅读thisJava: when to use static methods?并观看this

有多种方法可以让它发挥作用。但是,请避免使用static(如果您不知道正确使用它,会发生意外情况),并且main()内部会这样:

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

最后,我想你了解我。