So I am working on this game where I have a high score stored in a text file. I am following the newboston's tutorial on how to read and write to file. Right now I am testing whether the read class works and it is not working. It says cannot find file when I put the text exactly like how it is and the file is in my package so I don't have to say a path. Here is the method code in my game using both read and write classes:
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;
}
}
Here is the read class:
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();
}
}
Also here is the write file. I am concerned that this class might not work either as it looks like it maybe creating a new file and writing to that new one when I just want to write to an existing file I already have called "highScore.txt" Anyways here is the write class:
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();
}
}
So I am wondering why it is not working and thanks in advance.