【发布时间】:2018-02-01 17:38:09
【问题描述】:
所以我正在开发这个游戏,我的高分存储在一个文本文件中。我正在关注 newboston 关于如何读取和写入文件的教程。现在我正在测试 read 类是否有效并且它不工作。当我完全按照原样放置文本并且文件在我的包中时,它说找不到文件,所以我不必说路径。这是我的游戏中使用读写类的方法代码:
private int getHighScore(int change, int newScore) {
if (change==1) {
readFile r=new readFile();
r.openFile();
String fileScore=r.readtext();
r.closeFile();
int score=Integer.parseInt(fileScore);
return score;
}
else {
writeToFile w=new writeToFile();
w.openFile();
w.addRecords(newScore);
w.closeFile();
return newScore;
}
}
这里是读取类:
import java.io.*;
import java.util.*;
public class readFile {
private Scanner read;
public void openFile() {
try {
read=new Scanner(new File("highScore.txt"));
}
catch(Exception e){
System.out.println("Could not find file.");
}
}
public String readtext() {
String score=read.next();
return score;
}
public void closeFile() {
read.close();
}
}
这里还有写文件。我担心这个类可能不起作用,因为它看起来可能会创建一个新文件并写入该新文件,而我只是想写入一个我已经称为“highScore.txt”的现有文件无论如何这里是写类:
import java.util.*;
public class writeToFile {
private Formatter x;
public void openFile() {
try {
x=new Formatter("highScore.txt");
}
catch(Exception e) {
System.out.println("Can not open that file.");
}
}
public void addRecords(int newScore) {
String score=""+newScore;
x.format("%s", score);
}
public void closeFile() {
x.close();
}
}
所以我想知道为什么它不起作用并提前感谢。
【问题讨论】:
-
你能发布堆栈跟踪吗?
-
要找出找不到文件的原因,请使用
File类中的.exists()和getPath或getAbsolutePath方法。请参阅:docs.oracle.com/javase/7/docs/api/java/io/File.html 考虑使用boolean而不是int作为change中的change变量@。 -
如何发布堆栈跟踪?
-
哦,堆栈跟踪是这样的:线程“main”中的异常找不到文件。 java.lang.NullPointerException at readFile.readtext(readFile.java:16) at Game.getHighScore(Game.java:474) at Game.updateTitle(Game.java:501) at Game.
(Game.java:107 ) 在 Game.main(Game.java:57) -
仍然有找不到文件的问题,如果我尝试使用路径仍然存在。我试过does文件存在,它说的是假的意思是它不存在,即使它确实存在。
标签: java file readfile writefile