如何在Java 5中从文本文件读取时间和日期? [英] How to Read Time and Date from Text File in Java 5?

查看:51
本文介绍了如何在Java 5中从文本文件读取时间和日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java 5 SE从纯文本文件中读取数据.数据采用以下格式:

I'm trying to read data from a plain text file using Java 5 SE. The data is in the following formats:

10:48 AM
07/21/2011

我已经研究过DateFormat和SimpleDateFormat,但是我想不出将这些数据读入Date对象的最直接的方法.

I've looked into DateFormat and SimpleDateFormat, but I can't figure out the most straight-forward way of reading this data into a Date object.

这是我到目前为止的内容:

Here's what I have so far:

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

class Pim {

    File dataFile;
    BufferedReader br;
    String lineInput;
    Date inputTime;
    Date inputDate;

    public Pim() {

        dataFile = new File("C:\\Data.txt");

        try {

            br = new BufferedReader(new FileReader(dataFile));

            lineInput = br.readLine();
            inputTime = new Date(lineInput);

            lineInput = br.readLine();
            inputDate = new Date(lineInput);            

            br.close();

        } catch (IOException ioe) {

            System.out.println("\n An error with the Data.txt file occured.");
        }
    }
}

我在这里正确吗?最好的方法是什么?

Am I on the right track here? What's the best way to do this?

推荐答案

首先将这两行连接起来,使其具有以下内容:字符串日期="2011年7月21日上午10:48"

First concat the two lines to have something like this: String date = "07/21/2011 10:48 AM"

DateFormat formatter = new SimpleDateFormat("MM/dd/yy h:mm a");
Date date = (Date)formatter.parse(date);

这应该可行,您可以参考 SimpleDateFormat API 了解更多选项.

This should work, you can refer to SimpleDateFormat API for more options.

这篇关于如何在Java 5中从文本文件读取时间和日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆