集册 Java实例教程 读取文本文件并显示每条记录。

读取文本文件并显示每条记录。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

609
读取文本文件并显示每个记录。

import java.io.IOException;

import java.nio.file.Paths;

import java.util.NoSuchElementException;/*来 自 N o w J a v a . c o m - 时  代  Java*/

import java.util.Scanner;


public class Main {

  private static Scanner input;


  public static void main(String[] args) {

    openFile();

    readRecords();

    closeFile();

  }


  // open file clients.txt

  public static void openFile() {

    try {

      input = new Scanner(Paths.get("clients.txt"));

    } catch (IOException ioException) {

      System.err.println("Error opening file. Terminating.");
      /**
       from
      * 时 代 J a v a 
      **/

      System.exit(1);

    }

  }


  // read record from file

  public static void readRecords() {

    System.out.printf("%-10s%-12s%-12s%10s%n", "Account", "First Name",

        "Last Name", "Balance");


    try {

      while (input.hasNext()) // while there is more to read

      {

        // display record contents

        System.out.printf("%-10d%-12s%-12s%10.2f%n", input.nextInt(),

            input.next(), input.next(), input.nextDouble());

      }

    } catch (NoSuchElementException elementException) {

      System.err.println("File improperly formed. Terminating.");

    } catch (
展开阅读全文