【发布时间】: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() 以确保它在那里,但我仍然得到异常