【问题标题】:Java Nullpointexception when creating a text file创建文本文件时出现 Java Nullpointerexception
【发布时间】:2014-02-13 17:40:47
【问题描述】:

我正在尝试在主目录中使用我在此类中创建的功能,但它崩溃并显示“警告:无法在根 0 处打开/创建首选项根节点 Software\JavaSoft\Prefs x80000002。 Windows RegCreateKeyEx(...) 返回错误代码 5。线程“主”java.lang.NullPointerException 中的异常 每当我尝试做grabar.touchFile();

这是我制作的课程:http://pastebin.com/eNWrp07f

package com.brackeen.javagamebook.grabar;

import java.io.*;

public class Grabar{
    private int mapaTexto;
    private String nombreArchivo = "Grabar.txt";

    public void touchFile() throws IOException{
        File f = new File(nombreArchivo);
        if (!f.isFile())
            f.createNewFile();
    }

    public int readFile() throws IOException{
        try{
            touchFile();
        } catch(IOException ex){
            ex.printStackTrace();
        }

        BufferedReader fileIn = new BufferedReader(new FileReader(nombreArchivo));
        String dato = fileIn.readLine();
        int mapaTexto = Integer.parseInt(dato);
        fileIn.close();
        return mapaTexto;
    }

    public void writeFile(int n) throws IOException{
        try{
            touchFile();
        } catch(IOException ex){
            ex.printStackTrace();
        }
        PrintWriter fileOut = new PrintWriter(new FileWriter(nombreArchivo));
        fileOut.println(n);
        fileOut.close();
    }

}

【问题讨论】:

  • NullPointerException 在哪里?如果没有实际的错误消息,很难为您提供帮助。
  • 请注意,如果文件Grabar.txt 不存在,那么它会创建一个新文件,并且会抛出一个NumberFormatException @ 这一行int mapaTexto = Integer.parseInt(dato);
  • 另请注意,如果此目录结构不存在,com/brackeen/javagamebook 它会NOT CREATE 该结构中任何丢失的文件夹,因此将抛出 IOException @ @ 987654329@。因此这两种情况都会抛出异常!
  • 我已经编辑了帖子,但有例外。这是主要的pastebin.com/VvBPdyS6 我在第 92 行和第 531 行中使用了这个类。该目录存在,但为了确保我只使用“Grabar.txt”进行了尝试,这两种异常都不起作用。我尝试在每次读写中执行 touchFile() 以确保它在那里,但我仍然得到异常

标签: java nullpointerexception


【解决方案1】:

查看您的 pastebin 转储,问题不在于您的 Grabar 类,而在于您的 GameManager 类的 init() 函数。您正在尝试在您的 Grabar 实例上调用 touchFile(),但您尚未使用 new 运算符创建一个。

init() 方法中的touchFile() 方法之前添加此行:

grabar = new Grabar();

【讨论】:

  • 哇,非常感谢!我不敢相信这是这么愚蠢的事情!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
相关资源
最近更新 更多