Java Formatter不写入文件

时间:2018-11-08 14:20:30

标签: java

我已编写此代码,该代码应将一系列用户输入保存到txt文件中,以备后用。我的程序创建了一个.txt文件,但未在其中写入任何内容

// 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 
    }   
}

2 个答案:

答案 0 :(得分:2)

您必须使用output.format,最好使用output.flush将格式化程序实例写入的内容刷新到文件中。

这是一个工作版本,它要求用户输入并写入文件,然后立即将其刷新。使用资源尝试后,文件也将关闭。

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);
    }

}

答案 1 :(得分:1)

因为您没有向文件写入任何内容。
 output.write(DataYouWantToWrite) 如果我记得正确,那是您需要调用的方法。