我正在尝试使用 Java 5 SE 从纯文本文件中读取数据。数据采用以下格式:
10:48 AM
07/21/2011
我研究过 DateFormat 和 SimpleDateFormat,但我想不出将这些数据读入 Date 对象的最直接的方法。
这是我目前所拥有的:
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.");
}
}
}
我走在正确的轨道上吗?执行此操作的最佳方法是什么?
最佳答案
首先将这两行连接成这样: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更多选项。
关于java - 如何在 Java 5 中从文本文件中读取时间和日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6768405/