【问题标题】:Why can't the elements of my array be parsed properly?为什么我的数组的元素不能被正确解析?
【发布时间】:2019-12-09 18:00:55
【问题描述】:

Java 新手,我正在学习 InputStream 类,并尝试实现我在 Cay S. Horstmann 的 Core Java Volume II,第十版中找到的代码。此代码应该通过将数组中的数据保存和读取到文件中来显示 Input/OutputStream 类在读取字节序列时如何有用。它首先声明具有给定字符串和 int 数字的数组,将此数组的元素保存在 .dat 文件中,从 .dat 文件中读取元素并在控制台中显示它们。

但我在控制台中得到了这个:

Exception in thread "main" java.time.format.DateTimeParseException: Text '0' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)
    at java.time.LocalDate.parse(LocalDate.java:385)
    at chapter2.TextFileTest.readEmployee(TextFileTest.java:100)
    at chapter2.TextFileTest.readData(TextFileTest.java:76)  
    at chapter2.TextFileTest.main(TextFileTest.java:35)  
C:\Users\barcejo1\AppData\Local\NetBeans\Cache\8.2\executor-snippets  \run.xml:53: Java returned: 1
BUILD FAILED (total time: 21 seconds)

似乎问题出在将每行的 int 数分别解析为将写入 .dat 文件中的变量时。我复制了这段代码,但我不明白为什么它不起作用。
我期待严厉的回答,没关系。我很高兴接受教育。

import java.io.*;
import java.time.*;
import java.util.*;

/*** @version 1.14 2016-07-11
* @author Cay Horstmann
*/
public class TextFileTest
{
    public static void main(String[] args) throws IOException
    {
     Employee[] staff = new Employee[3];

     staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
     staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
     staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

     // save all employee records to the file employee.dat
        try (PrintWriter out = new PrintWriter("employee.dat", "UTF-8"))
        {
        writeData(staff, out);
        }

     // retrieve all records into a new array
        try (Scanner in = new Scanner(new FileInputStream("employee.dat"), "UTF-8"))
        {
        Employee[] newStaff = readData(in);

            // print the newly read employee records
            for (Employee e : newStaff)
            System.out.println(e);
        }
    }

     //Writes all employees in an array to a print writer

    private static void writeData(Employee[] employees, PrintWriter out) throws IOException
    {
       // write number of employees
       out.println(employees.length);

       for (Employee e : employees)
       writeEmployee(out, e);
    }

     /**
     * Reads an array of employees from a scanner
     * @param in the scanner
     * @return the array of employees
     */
    private static Employee[] readData(Scanner in)
    {
       // retrieve the array size
       int n = in.nextInt();
       in.nextLine(); // consume newline

       Employee[] employees = new Employee[n];
       for (int i = 0; i < n; i++)
     {
        employees[i] = readEmployee(in);
     }
       return employees;
    }

     /**
     * Writes employee data to a print writer
     * @param out the print writer
     */
    public static void writeEmployee(PrintWriter out, Employee e)
    {
       out.println(e.getName() + "|" + e.getSalary() + "|" + e.getHireDay());
    }

     /**
     * Reads employee data from a buffered reader
     * @param in the scanner
     */
    public static Employee readEmployee(Scanner in)
    {
       String line = in.nextLine();
       String[] tokens = line.split("\\|");
       String name = tokens[0];
       double salary = Double.parseDouble(tokens[1]);
       LocalDate hireDate = LocalDate.parse(tokens[2]);
       int year = hireDate.getYear();
       int month = hireDate.getMonthValue();
       int day = hireDate.getDayOfMonth();
       return new Employee(name, salary, year, month, day);
    }
}

【问题讨论】:

  • 堆栈跟踪显示错误发生在 readEmployee 的第 100 行。使用调试器并在该行设置断点以检查变量的值。或者简单地添加 println() 语句以了解它们包含的内容。这应该告诉你发生了什么。还可以使用文本编辑器阅读您的 .dat 文件以检查其中包含的内容。

标签: java datetime parsing inputstream printwriter


【解决方案1】:

您的代码不起作用,因为您只是在文件中写入 day。 下面是固定代码:

 package com.example.demo;

import java.io.*;
import java.time.*;
import java.util.*;

/***
 * @version 1.14 2016-07-11
 * @author Cay Horstmann
 */
public class TextFileTest {
    public static void main(String[] args) throws IOException {
        Employee[] staff = new Employee[3];

        staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
        staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
        staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

        // save all employee records to the file employee.dat
        try (PrintWriter out = new PrintWriter("employee.dat", "UTF-8")) {
            writeData(staff, out);
        }

        // retrieve all records into a new array
        try (Scanner in = new Scanner(new FileInputStream("employee.dat"), "UTF-8")) {
            Employee[] newStaff = readData(in);

            // print the newly read employee records
            for (Employee e : newStaff)
                System.out.println(e);
        }
    }

    //Writes all employees in an array to a print writer

    private static void writeData(Employee[] employees, PrintWriter out) throws IOException {
        // write number of employees
        out.println(employees.length);

        for (Employee e : employees)
            writeEmployee(out, e);
    }

    /**
     * Reads an array of employees from a scanner
     * 
     * @param in the scanner
     * @return the array of employees
     */
    private static Employee[] readData(Scanner in) {
        // retrieve the array size
        int n = in.nextInt();
        in.nextLine(); // consume newline

        Employee[] employees = new Employee[n];
        for (int i = 0; i < n; i++) {
            employees[i] = readEmployee(in);
        }
        return employees;
    }

    /**
     * Writes employee data to a print writer
     * 
     * @param out the print writer
     */
    public static void writeEmployee(PrintWriter out, Employee e) {
        //System.out.println(LocalDate.of(e.getYear(), e.getMonth(), e.getHireDay()).toString());
        out.println(e.getName() + "|" + e.getSalary() + "|" + LocalDate.of(e.getYear(), e.getMonth(), e.getHireDay()).toString());
    }

    /**
     * Reads employee data from a buffered reader
     * 
     * @param in the scanner
     */
    public static Employee readEmployee(Scanner in) {
        String line = in.nextLine();
        String[] tokens = line.split("\\|");
        String name = tokens[0];
        double salary = Double.parseDouble(tokens[1]);
        LocalDate hireDate = LocalDate.parse(tokens[2]);
        int year = hireDate.getYear();
        int month = hireDate.getMonthValue();
        int day = hireDate.getDayOfMonth();
        return new Employee(name, salary, year, month, day);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多