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.

Recommended Answers

All 39 Replies

read your contents in as (for instance) an ArrayList of Strings, and just add the lines you want to be added in your file.

later on, when you write the file, write the lines contained in that ArrayList, which contains the original contents as well as the new lines.

read your contents in as (for instance) an ArrayList of Strings, and just add the lines you want to be added in your file.

later on, when you write the file, write the lines contained in that ArrayList, which contains the original contents as well as the new lines.

Please help me with the code? :(

first thing to do is create one file with two methods:
1. a method to read the file, which takes a fileName and stores every line you read in a new ArrayList, and which later on you return
2. a method to write the file, which takes a fileName and an ArrayList of String elements, and writes these lines in your file.

also, you can add a main method to test them, but also an important part: don't throw exceptions in your main method. the main method is the very last place where you can catch and handle exceptions, and thus avoiding complete system crashes of your application.

all you need to do is adjust the code you have a bit, and you'll be fine.

first thing to do is create one file with two methods:
1. a method to read the file, which takes a fileName and stores every line you read in a new ArrayList, and which later on you return
2. a method to write the file, which takes a fileName and an ArrayList of String elements, and writes these lines in your file.

also, you can add a main method to test them, but also an important part: don't throw exceptions in your main method. the main method is the very last place where you can catch and handle exceptions, and thus avoiding complete system crashes of your application.

all you need to do is adjust the code you have a bit, and you'll be fine.

I'm new in java language :(.

I would be breaking forum rules by giving you the code. you first have to show that you have done some effort to do this yourself, but until now, all I've seen is some ... rather bad code (having your main method throwing an Exception???) that you copied from somewhere.

try what I suggested above step by step.
for instance, first try to put what you have now in it's own methods. if you keep it in it's own main method, you won't be able to use it in your application anyway.

I would be breaking forum rules by giving you the code. you first have to show that you have done some effort to do this yourself, but until now, all I've seen is some ... rather bad code (having your main method throwing an Exception???) that you copied from somewhere.

try what I suggested above step by step.
for instance, first try to put what you have now in it's own methods. if you keep it in it's own main method, you won't be able to use it in your application anyway.

Its still the same. When i close it and put a new text its change

import java.io.*;
import java.util.*;

public class WriteTextFileExample{
  public static void main(String[] args)throws IOException{
      ArrayList<String> name= new ArrayList<String>();
      ArrayList<String> thescore = new ArrayList<String>();
      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));
  String line = null;
          if ((line = guess.readLine()) != null) {
           name.add(line);
  }
  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 scoresiam = c;
  output.write(scoresiam);
  output.close();
  System.out.println("Your file has been written");  
 
  
  }
}

yessssss... I know very well it is, since you haven't changed anything in your code.
you also still haven't tried to move it into another method as I suggested.

yessssss... I know very well it is, since you haven't changed anything in your code.
you also still haven't tried to move it into another method as I suggested.

Dude i change a few line (-.-). But it doesn't work. I told you i'm new. :(

yes, you added some lines which have no effect on what you are trying to do.
some of the lines you added you don't even use.

if you're truly just a beginner, it might be better to start off with simpler tasks to get to know the language. in that way, it will be a lot easier to understand what you have to do and what I've suggested you to do.

yes, you added some lines which have no effect on what you are trying to do.
some of the lines you added you don't even use.

if you're truly just a beginner, it might be better to start off with simpler tasks to get to know the language. in that way, it will be a lot easier to understand what you have to do and what I've suggested you to do.

I'm looking to it. I just need it urgently. :(

why do you need it urgently? if it's for a class, no doubt everything you need to know is in your syllabus, and has been dealt with in your class.

take a look at this part of your code:

File file = new File("Name.txt");
output = new BufferedWriter(new FileWriter(file));
String line = null;
if ((line = guess.readLine()) != null) {
name.add(line);
}
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();

the only thing you are writing that you entered yourself, is the name1 variable (or the value that you've stored there in)

now, if you have this in a method, which takes a List filled with String objects
you could have something like this:

List<String> passedList = new ArrayList<String>();
File file = new File("Name.txt");
output = new BufferedWriter(new FileWriter(file));
String line = null;
if ((line = guess.readLine()) != null) {
name.add(line);
}
output.write(text);
output.write("\r\n");
System.out.print("Write your name: ");
String b= guess.readLine();
passedList.add(b);
for ( String toWrite: passedList ){
output.write(toWrite);
}
output.close();

take a look at what I changed, and what you think the difference is

why do you need it urgently? if it's for a class, no doubt everything you need to know is in your syllabus, and has been dealt with in your class.

take a look at this part of your code:

File file = new File("Name.txt");
output = new BufferedWriter(new FileWriter(file));
String line = null;
if ((line = guess.readLine()) != null) {
name.add(line);
}
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();

the only thing you are writing that you entered yourself, is the name1 variable (or the value that you've stored there in)

now, if you have this in a method, which takes a List filled with String objects
you could have something like this:

List<String> passedList = new ArrayList<String>();
File file = new File("Name.txt");
output = new BufferedWriter(new FileWriter(file));
String line = null;
if ((line = guess.readLine()) != null) {
name.add(line);
}
output.write(text);
output.write("\r\n");
System.out.print("Write your name: ");
String b= guess.readLine();
passedList.add(b);
for ( String toWrite: passedList ){
output.write(toWrite);
}
output.close();

take a look at what I changed, and what you think the difference is

My instructor still don't teach us using the ArrayList. Were still on the function of array and using a public static void main (String args[]) only. (-.-). Dude I get this. But. Everytime i rune the program the content change when i put a new line :(.

that is because you don't write the original contents of your file.
you overwrite it.

that is because you don't write the original contents of your file.
you overwrite it.

But how? I will use a arraylist? To the file saved? Like

File file = new File("Name.txt"); //I will put a arraylist in here?

take a closer look at your FileRead class. there you read what 's in your file, you just print it.
now, instead of printing these values, store them in an ArrayList which later on you use to add your new lines to.

take a closer look at your FileRead class. there you read what 's in your file, you just print it.
now, instead of printing these values, store them in an ArrayList which later on you use to add your new lines to.

Like this?

FileInputStream fstream = new FileInputStream("Name.txt");
  List<String> Names= new ArrayList<String>();
  // 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
  Names.add(strLine);
  }
  //Close the input stream
  in.close();

yup, now about the same for the writing

yup, now about the same for the writing

When i putted it on the writing it's infinite loop.

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));
     while ((text = guess.readLine()) != null)   {
  // Print the content on the console
  passedList.add(text);
  }
  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");

you had to add something similar.
you already have your contents, that's what you get by reading your file and adding a few lines, you did that in your previous post.
so, now you have an ArrayList filled with Strings, what are actually lines of text you want to write in that order to your file.

so:

List<String> myList; // this is the list you have from your other code
for ( String line : myList ){
  writeLineInFile(); 
// I just put a method name here to give you the idea
// of what to do, not the actual code, but if you take a look at your own code
// this is all you need to complete it
}

you had to add something similar.
you already have your contents, that's what you get by reading your file and adding a few lines, you did that in your previous post.
so, now you have an ArrayList filled with Strings, what are actually lines of text you want to write in that order to your file.

so:

List<String> myList; // this is the list you have from your other code
for ( String line : myList ){
  writeLineInFile(); 
// I just put a method name here to give you the idea
// of what to do, not the actual code, but if you take a look at your own code
// this is all you need to complete it
}

I'm still thinking on the code you give. Woooh. I'm almost here for almost 5 hours waiting for your answers. But still isn't finish. :| . The writeLineInFile(); code doesn't work on me :(

well, of course it doesn't work, it's not an existing method, as I explained in the comments, you need to replace that line by code you already had and that does work for you

well, of course it doesn't work, it's not an existing method, as I explained in the comments, you need to replace that line by code you already had and that does work for you

Still the same. It changes when i put a new one :(

for(String line: passedList){
        output.write(line);
    }

ow key ... can you show me your entire method instead of just this snippet?

Here

import java.io.*;
import java.util.*;

public class WriteandReadTextFileExample{
  public static void main(String[] args)throws IOException{
      ArrayList<String> passedList= new ArrayList<String>();
      ArrayList<String> thescore = new ArrayList<String>();
      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));
  for(String line: passedList){
        output.write(line);
    }
    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 scoresiam = c;
  output.write(scoresiam);
  output.close();
  System.out.println("Your file has been written");  
  
  try{
  // Open the file that is the first 
  // command line parameter
  FileInputStream fstream = new FileInputStream("Name.txt");
  List<String> Names= new ArrayList<String>();
  // 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
  Names.add(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());
  }
  }
}

you are writing your file before you read your data, what did you expect would happen?

a few remarks, I've made them before, but just to summarize:

1. separate your code in methods: one that takes a fileName, and that returns an ArrayList which contains the contents of that file
2. create a method which takes the ArrayList as a parameter, in which you read your new information and add it to the ArrayList, which you then return (the ArrayList)
3. create a method which takes a fileName and the ArrayList as parameters, and which write the entire contents of that ArrayList (being the original contents ánd the new contents) to the file.

when you've done this: call these methods IN THIS VERY ORDER from your main method.
don't add reading functionality to your writing method or vice versa.

and DO NOT allow your main method to throw any Exception. as I've explained before, the main metghod is the very last place where you can catch and handle an exception.

if you don't know how to create a method:

public static void main(String[] args){
  int x = 3;
  x = x + 5;
  System.out.println("x = " + x);
}

can also be written as:

public static void main(String[] args){
  int x = initializeX();
  x = augmentX(x);
  printValue(x);
}

public static int initializeX(){
  return 3;
}

public static int augmentX(int originalX){
  originalX+=5;
  return originalX;
}

public static void printValue(int x){
  System.out.println("x = " + x);
}

you are writing your file before you read your data, what did you expect would happen?

a few remarks, I've made them before, but just to summarize:

1. separate your code in methods: one that takes a fileName, and that returns an ArrayList which contains the contents of that file
2. create a method which takes the ArrayList as a parameter, in which you read your new information and add it to the ArrayList, which you then return (the ArrayList)
3. create a method which takes a fileName and the ArrayList as parameters, and which write the entire contents of that ArrayList (being the original contents ánd the new contents) to the file.

when you've done this: call these methods IN THIS VERY ORDER from your main method.
don't add reading functionality to your writing method or vice versa.

and DO NOT allow your main method to throw any Exception. as I've explained before, the main metghod is the very last place where you can catch and handle an exception.

if you don't know how to create a method:

public static void main(String[] args){
  int x = 3;
  x = x + 5;
  System.out.println("x = " + x);
}

can also be written as:

public static void main(String[] args){
  int x = initializeX();
  x = augmentX(x);
  printValue(x);
}

public static int initializeX(){
  return 3;
}

public static int augmentX(int originalX){
  originalX+=5;
  return originalX;
}

public static void printValue(int x){
  System.out.println("x = " + x);
}

Why so hard? :(

Why so hard? :(

Actually stultuske's post is suppose to make the program a lot easier to handle and use

which part are you having problems understanding?

I'm not trying to make it hard, or to sound hard, but apparently you don't understand what I'm trying to tell you.

you are mixing up your input and output functionalities, and you either don't implement the changes I suggest, or you implement them in a way they won't work.

It's not easy to give "easy-for-starters" hints if you're trying to develop an application that is usually out of a "fresh-starter" reach.

Actually stultuske's post is suppose to make the program a lot easier to handle and use

which part are you having problems understanding?

The part that when i put a new one it changes :|

I'm not trying to make it hard, or to sound hard, but apparently you don't understand what I'm trying to tell you.

you are mixing up your input and output functionalities, and you either don't implement the changes I suggest, or you implement them in a way they won't work.

It's not easy to give "easy-for-starters" hints if you're trying to develop an application that is usually out of a "fresh-starter" reach.

It's my instructor said. :|

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.