【问题标题】:Java file context that is not null throws NullPointerException [duplicate]不为空的 Java 文件上下文抛出 NullPointerException [重复]
【发布时间】:2017-06-11 19:27:57
【问题描述】:

我的程序为我可以制作的游戏创建文件,它有一个名为 Update 的方法,它在程序启动时运行,读取文件夹“mob”中的所有文件,当没有文件时它运行良好,但是,如果在 mobs 文件夹中创建一个文件,其中包含内容,当程序运行时,尽管文件中的上下文不为空,但它会抛出 NullPointerException。

顺便说一句,这是一个 JavaFX FXML 程序

FXMLDocumentController

package fightwriter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

public class FXMLDocumentController implements Initializable {

    String content;

    @FXML // fx:id="TFname"
    private TextField TFname; // Value injected by FXMLLoader

    @FXML // fx:id="TFhp"
    private TextField TFhp; // Value injected by FXMLLoader

    @FXML // fx:id="TFattMin"
    private TextField TFattMin; // Value injected by FXMLLoader

    @FXML // fx:id="TFattH"
    private TextField TFattH; // Value injected by FXMLLoader

    @FXML // fx:id="TFdex"
    private TextField TFdex; // Value injected by FXMLLoader

    @FXML // fx:id="TFpots"
    private TextField TFpots; // Value injected by FXMLLoader

    @FXML // fx:id="TFspAtt1Name"
    private TextField TFspAtt1Name; // Value injected by FXMLLoader

    @FXML // fx:id="TFspAtt1M"
    private TextField TFspAtt1M; // Value injected by FXMLLoader

    @FXML // fx:id="TFspAtt1H"
    private TextField TFspAtt1H; // Value injected by FXMLLoader

    @FXML // fx:id="TFspAtt2Name"
    private TextField TFspAtt2Name; // Value injected by FXMLLoader

    @FXML // fx:id="TFspAtt2M"
    private TextField TFspAtt2M; // Value injected by FXMLLoader

    @FXML // fx:id="TFspAtt2H"
    private TextField TFspAtt2H; // Value injected by FXMLLoader

    @FXML // fx:id="create"
    private Button create; // Value injected by FXMLLoader

    @FXML // fx:id="ErrorMsgs"
    private TextArea ErrorMsgs; // Value injected by FXMLLoader

    @FXML // fx:id="list"
    private TextArea list; // Value injected by FXMLLoader

    @FXML // fx:id="save"
    private Button save; // Value injected by FXMLLoader

    @FXML
    void createOnAction(ActionEvent event) {
        ErrorMsgs.setText("");
        try {
            File mobs = new File(System.getProperty("user.dir") + "\\mobs");
            mobs.mkdir();
            FileWriter fw = new FileWriter(new File(System.getProperty("user.dir") + "\\mobs\\" + TFname.getText() + ".mob"));
            try (BufferedWriter bw = new BufferedWriter(fw)) {
                bw.write("name=" + TFname.getText() + "\r\nhp=" + TFhp.getText() + "\r\nattM=" + TFattMin.getText() + "\r\n"
                        + "attH=" + TFattH.getText() + "\r\ndex=" + TFdex.getText() + "\r\npots=" + TFpots.getText() + "\r\n"
                        + "spAtt1Name=" + TFspAtt1Name.getText() + "\r\nspAtt1M=" + TFspAtt1M.getText() + "\r\nspAtt1H=" + TFspAtt1H.getText() + "\r\n"
                        + "spAtt2Name=" + TFspAtt2Name.getText() + "\r\nspAtt2M=" + TFspAtt2M.getText() + "\r\nspAtt2H=" + TFspAtt2H.getText());
            }
        } catch (IOException ex) {
            ErrorMsgs.appendText(ex.getMessage());
        }
        Update();
    }

    @FXML
    void saveOnAction(ActionEvent event) {
        ErrorMsgs.setText("");
        Update();
    }

    public void Update() {
        File mobs = new File(System.getProperty("user.dir") + "\\mobs");
        File[] lists = mobs.listFiles();
        if (lists != null) {
            for (File f : lists) {
                try {
                    content = new Scanner(f).useDelimiter("\\Z").next();
                    if (content != null) {
                        ***list.appendText(content + "\n\n\n\n\n\n");***
                    }
                } catch (FileNotFoundException ex) {
                    ErrorMsgs.appendText(ex.getMessage());
                }
            }
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }

}

FXML 文档

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Separator?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="759.0" prefWidth="1104.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fightwriter.FXMLDocumentController">
    <children>
        <TextField fx:id="TFname" layoutX="41.0" layoutY="35.0" promptText="Name" />
        <TextField fx:id="TFhp" layoutX="41.0" layoutY="89.0" promptText="Health" />
        <TextField fx:id="TFattMin" layoutX="41.0" layoutY="145.0" promptText="Minimum Attack" />
        <TextField fx:id="TFattH" layoutX="41.0" layoutY="204.0" promptText="Maximun Attack" />
        <TextField fx:id="TFdex" layoutX="41.0" layoutY="260.0" promptText="Dexterity" />
        <TextField fx:id="TFpots" layoutX="41.0" layoutY="318.0" promptText="# of Health Potions" />
        <TextField fx:id="TFspAtt1Name" layoutX="41.0" layoutY="373.0" promptText="Special Attack 1 Name" />
        <TextField fx:id="TFspAtt1M" layoutX="41.0" layoutY="428.0" promptText="Special Attack 1 min dmg" />
        <TextField fx:id="TFspAtt1H" layoutX="41.0" layoutY="486.0" promptText="Special Attack 1 max dmg" />
        <TextField fx:id="TFspAtt2Name" layoutX="41.0" layoutY="543.0" promptText="Special Attack 2 Name" />
        <TextField fx:id="TFspAtt2M" layoutX="41.0" layoutY="600.0" promptText="Special Attack 2 min dmg" />
        <TextField fx:id="TFspAtt2H" layoutX="41.0" layoutY="658.0" prefHeight="31.0" prefWidth="187.0" promptText="Special Attack 2 max dmg" />
        <Separator layoutX="604.0" orientation="VERTICAL" prefHeight="760.0" prefWidth="0.0" />
        <Button fx:id="create" layoutX="42.0" layoutY="702.0" mnemonicParsing="false" onAction="#createOnAction" prefHeight="31.0" prefWidth="77.0" text="Create" />
        <TextArea fx:id="ErrorMsgs" editable="false" layoutX="240.0" layoutY="35.0" prefHeight="698.0" prefWidth="351.0" promptText="ErrorMsgs" />
        <TextArea fx:id="list" editable="false" layoutX="629.0" layoutY="21.0" prefHeight="711.0" prefWidth="448.0" />
        <Button fx:id="save" layoutX="135.0" layoutY="702.0" mnemonicParsing="false" onAction="#saveOnAction" text="Update List" />
    </children>
</AnchorPane>

FightWriter(主类)

package fightwriter;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class FightWriter extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();

        FXMLDocumentController L = new FXMLDocumentController();
        ***L.Update();***
    }

    public static void main(String[] args) {
        launch(args);
    }

}

错误

Executing C:\Users\21114693\Documents\NetBeansProjects\FightWriter\dist\run803916352\FightWriter.jar using platform C:\Program Files\Java\jdk1.8.0_102\jre/bin/java
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at fightwriter.FXMLDocumentController.Update(FXMLDocumentController.java:103)
    at fightwriter.FightWriter.start(FightWriter.java:21)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Exception running application fightwriter.FightWriter
Java Result: 1
Deleting directory C:\Users\21114693\Documents\NetBeansProjects\FightWriter\dist\run803916352

【问题讨论】:

  • 我们需要知道错误发生的行和完整的堆栈跟踪。
  • 哦,是的,谢谢,我忘记了,非常感谢
  • 为什么每个人在阅读“How to use a debugger”之类的内容之前都会问这样的问题?
  • 什么?在未捕获的 NPE 上下断点,启动你的程序并不简单?
  • @MineRockers 当然,这不是断点的作用。他们只是告诉调试器在预定义的行暂停程序的执行,以便您可以调查并查看您使用的变量的值是什么。在您的情况下,您可以使用它来查找导致您的NullPointerException

标签: java file if-statement javafx nullpointerexception


【解决方案1】:

如果您查看堆栈跟踪,您会发现可能是 null 的唯一变量是 list

if (content != null) {
    list.appendText(content + "\n\n\n\n\n\n"); // <-- line from stacktrace
}

这可能看起来令人困惑,因为您之前这样做过:

if (lists != null) {

但这是另一个变量(注意“s”)。 list 声明旁边的以下评论显然不是真的:

@FXML // fx:id="list"
private TextArea list; // Value injected by FXMLLoader

我对 JavaFX 没有太多经验,但我认为在 FXMLLoader 完成工作之前调用了您的代码。

【讨论】:

  • FXMLLoader 是使用 JavaFx Scene Builder 生成我的方法的。变量列表是TextArea,列表是文件夹“Mob”中的文件列表列表是文本区域,而不是字符串
  • 谁说它是字符串? String 没有名为appendString() 的方法。很明显,list 在执行代码时(尚未)初始化。把if (content != null) {改成if (content != null &amp;&amp; list != null) {看看效果如何(如果还是死机,就在别的地方了)。
  • 错误消失了,但文件中的数据没有显示在文本区域中
  • 还有一件奇怪的事情,当我点击调用更新方法的更新列表时,只读取并显示了1个文件,我有3个
  • @MineRockers 请参阅我在 OP 中的评论。您没有在控制器上调用 Update,因此它不会影响 UI 中的任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-23
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多