Deevena Sista
Deevena Sista

Reputation: 23

Java Formatter not Writing to File

I have written this code that should save a series of user input into a txt file for later use. My program creates a .txt file but does not write anything in it

// Fig. 6.30: CreateTextFile.java
// Writing data to a sequential text file with class Formatter.
import java.util.Formatter;
import java.util.Scanner;

public class CreateTextFile {

    public static void main(String[] args) throws Exception {

         Formatter output = new Formatter( "students.txt" ); // open the file
         Scanner input = new Scanner( System.in );      // reads user input 

        String fullName;        // stores student's name 
        int age;                // stores age
       String grade;            // stores grade
       double gpa;          // stores gpa

       System.out.println( "Enter student name, age, grade, and gpa."); 

       while ( input.hasNext() ) { // loop until end-of-file indicator
           // retrieve data to be output 
           fullName = input.next(); // read full name
          age = input.nextInt(); // read age
          grade = input.next(); // read grade 
          gpa = input.nextDouble(); // read gpa

       } // end while 

    output.close(); // close file 
    }   
}

Upvotes: 1

Views: 415

Answers (2)

gil.fernandes
gil.fernandes

Reputation: 14611

You have to use output.format and ideally also output.flush to flush the content written by the formatter instance to the file.

Here is a working version which asks the user for input and writes to the file flushing it immediately afterwards. The file is also closed after execution using try with resources.

public static void main(String[] args) throws Exception {

    try(Formatter output = new Formatter( "students.txt" )) { // open the file
        Scanner input = new Scanner(System.in);      // reads user input

        String fullName;        // stores student's name
        int age;                // stores age
        String grade;            // stores grade
        double gpa;          // stores gpa


        do { // loop until end-of-file indicator
            System.out.println("Enter student name, age, grade, and gpa or type 'q' to quit");
            // use nextLine, if reading input with spaces in this case
            fullName = input.nextLine(); // read full name
            if ("q".equals(fullName)) {
                break;
            }
            age = input.nextInt(); // read age
            grade = input.next(); // read grade
            gpa = input.nextDouble(); // read gpa
            output.format("fullName: %s; age: %s; grade: %s; gpa: %s%n", fullName, age, grade, gpa);
            output.flush();
        } while (true);
    }

}

Upvotes: 2

Because you are not writing anything to the file.
output.write(DataYouWantToWrite) If i remember correct is the method you need to call.

Upvotes: 1

Related Questions