Hi all,

I got a code in 2 programs that allow me to open the file, write the file, then close it.

BUT...I want to open it back up and read it then close it again and i don't know how to. Below is what i already have but i don't know how to code it to open back up and read the contents of the file.

Help...anyone?

import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Formatter;
import java.util.FormatterClosedException;

public class NumberStudy
{
  private Formatter output; // sends the text to a file
  
    //allow the user to open a file
	public void openFile()
	{
	  try
	  {
	    output = new Formatter( "numbers.txt" );
	  } //end try

	  catch (SecurityException securityException)
	  {
	    System.err.println( "You do not have right access to this file.");
		System.exit(1);
	  } // end catch

	catch (FileNotFoundException filesNotFoundException)
{
	System.err.println("Error creating file. ");
	System.exit(1);
}
}
	 
	 //add records to file
	 public void addRecords()
	 {
		Scanner input = new Scanner(System.in);
	   
	   System.out.printf("%s\n%s\n%s\n%s", "Please enter your survey responses.", "To Exit: " , "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", "On Windows type <ctrl> z then press Enter");

	   System.out.printf("%s", "Enter your survey result.");
	   
	   while (input.hasNext()) // loop until end-of-file indicator
	   {
	     try // output values to file
		 {
		//retrieve data to be output
		  int newvalue = input.nextInt(); //read rating
	     
		//write a new record
		 output.format( "%s\n", new Integer(newvalue).toString());
	
		 } //end try
		 catch (FormatterClosedException formatterClosedException)
		 {
		   System.err.println("Error writing to file. ");
		   return;
		 } // end catch
		 catch (NoSuchElementException elementException)
		 {
		   System.err.println("Invalid input. Please try again. ");
		   input.nextLine(); //discard input so user can try again
		 } // end catch

		 System.out.printf("%s", "Enter your survey result.");
		 }
	}
	
	//close file
	public void closeFile()
	{
	  if (output != null)
	     output.close();

	}  //end method

} //end class
public class NumberStudyTest
{
  public static void main(String args[])
  {
    NumberStudy application = new NumberStudy();
	
	application.openFile();
	application.addRecords();
	application.closeFile();
	} // end main
} // end class

thanx ezzaral.

I'll try that now

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.