我正在尝试使用 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);
这个应该可以的,可以参考一下简单日期格式 API http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html以获得更多选择。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)