gpt4 book ai didi

创建文本文件时Java NullpointerException

转载 作者:行者123 更新时间:2023-12-01 23:50:11 27 4
gpt4 key购买 nike

我试图在主类中使用我在此类中创建的函数,但它崩溃并显示“警告:无法在根 0 处打开/创建首选项根节点 Software\JavaSoft\Prefsx80000002。 Windows RegCreateKeyEx(...) 返回错误代码 5。线程“main”中出现异常 java.lang.NullPointerException每当我尝试执行grabar.touchFile();

这是我制作的类(class):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();
}

}

最佳答案

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

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

grabar = new Grabar();

关于创建文本文件时Java NullpointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16410763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com