Java 格式化程序不写入文件

标签 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 
    }   
}

最佳答案

您必须使用 output.format 并且理想情况下还可以使用 output.flush 将格式化程序实例写入的内容刷新到文件中。

这是一个工作版本,它要求用户输入并写入文件,然后立即将其刷新。该文件在使用 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);
    }

}

关于Java 格式化程序不写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209647/

相关文章:

java - 通过互联网实现下载文件的简历

java - 我可以向 JLabel 添加 Action 监听器吗?

java - Java 代码中的 Kotlin 集成?

java - 在 itext 7 中将 html 转换为 pdf 时如何仅获得某些页面的横向方向?

java - 在哪里配置使用 GWT uploader 上传文件的路径?

java - gradle 无法检测到模块

java - 从 R.ID 接收微调器给出 NullPointerException

java - 用于删除 Postgresql 中逻辑冗余条目的 Cron 作业

java - 为什么 dir.mkdir() 不需要异常处理,而 file.createNewFile() 需要?

java - Tomcat 7 : How to set initial heap size correctly?