【问题标题】:FileOutputStream randomly writes null [closed]FileOutputStream 随机写入 null [关闭]
【发布时间】:2018-01-21 01:53:44
【问题描述】:

我有一个读取写入文件的程序。当我重新启动程序几次时,整个文件是空白,所以现在程序将无法启动。

编辑:

我已将主类添加到帖子中。

代码:

游戏类:

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 文件。并再次运行该程序。

任何帮助都非常感谢

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example
  • @AndrewThompson 我会看看我能做什么。
  • 这个程序的目的是什么。换句话说,你打算用这个来实现什么?
  • 再次,请考虑按照@AndrewThompson 40 分钟前的要求,在您的问题中创建和发布有效的minimal reproducible example。如果我们能够完全理解您的代码并运行它,我们就能更好地处理您的问题。
  • 再一次,改进你的问题。为我们提供无需修改即可复制、粘贴和运行的代码。是的,我们要求你工作,但你要求我们工作,这是你的问题,所以首当其冲的应该是你。

标签: java swing file


【解决方案1】:

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

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

所以读方法中data[0]的值为null。这是试图说服您的错误消息:

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

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

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

关于getProperty() 在文档中:

public String getProperty(String key)

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

参数: key - 属性键。

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

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

更新:

评论:抱歉,忘记在我的帖子中更改。整个文件 变为空/空白。

首先我不得不说你的完整代码不可编译(我必须做很多事情才能做到这一点)。

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

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 文件被创建。

原因是,你在调用read()之前没有调用write()

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

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

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

旁注:你在搞乱static 很多。

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

您可以通过多种方式使其发挥作用。但是避免使用static(如果你不知道正确使用它,会发生意想不到的事情)并且在main()内部这样做:

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

最后,我想你理解我了。

【讨论】:

  • 抱歉,忘记在我的帖子中更改了。整个文件变成null/blank。
  • @StarCoder 看看现在我已经更新了我的答案
  • 谢谢!我会尽力做到这一点,也感谢您的链接!现在阅读它们!
  • 好的,如果我在read() 之前调用write(),它不会覆盖文件吗?
  • @StarCoder 不会因为static 而发生,在做任何事情之前删除static 并通过main 方法中的实例进行访问。然后看看发生了什么(它对我有用)
猜你喜欢
  • 2011-01-28
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 2019-04-25
  • 2014-01-17
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多