Hi everyone! Here's my problem. I created a random guesser game (A school project) and then my instructor said they want them to put a hall of fame on the game. But... The problem is how do i put a hall of fame? If its saving 1 line per file. Like if you play the game again the score should be there. It should be display the name and the score of the player. So I already found a code.
import java.io.*;
public class WriteTextFileExample{
public static void main(String[] args)throws IOException{
int anArray[] = new int[100];
BufferedReader guess= new BufferedReader(new InputStreamReader(System.in));
Writer output = null;
System.out.print("Write your name: ");
String a= guess.readLine();
String text = a;
File file = new File("Name.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.write("\r\n");
System.out.print("Write your name: ");
String b= guess.readLine();
String name1 = b;
output.write(name1);
output.close();
System.out.println("Your file has been written");
System.out.print("Write the number: ");
String number = guess.readLine();
String numberdefine = number;
File scores = new File("Scores.txt");
output = new BufferedWriter(new FileWriter(scores));
output.write(numberdefine);
output.write("\r\n");
System.out.print("Write the number: ");
String c= guess.readLine();
String score = c;
output.write(score);
output.close();
System.out.println("Your file has been written");
}
}
FOR WRITING A TEXT FILE.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Name.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
FileInputStream score = new FileInputStream("Scores.txt");
// Get the object of DataInputStream
DataInputStream Scorenumber = new DataInputStream(score);
BufferedReader Number = new BufferedReader(new InputStreamReader(Scorenumber));
String ScoreLine;
//Read File Line By Line
while ((ScoreLine = Number.readLine()) != null) {
// Print the content on the console
System.out.println (ScoreLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
FOR READING THE TEXT FILE.
The problem is. Every time i open it again. The content of the file changes. :( Please help me?? I want to make the file content should remain and only added. THANKS ALOT.