如何在 Java 5 中从文本文件读取时间和日期?
我正在尝试使用 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.");
}
}
}
我走在正确的轨道上吗?最好的方法是什么?
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先将这两行连接起来,得到如下所示的内容: String date = "07/21/2011 10:48 AM"
这应该可以工作,您可以参考 SimpleDateFormat API 了解更多选项。
First concat the two lines to have something like this: String date = "07/21/2011 10:48 AM"
This should work, you can refer to SimpleDateFormat API for more options.
http://www.kodejava.org/examples/19.html
更改 SimpleDateFormat 参数根据你的格式。
http://www.kodejava.org/examples/19.html
Change the SimpleDateFormat param as per your format.
使用 Guava 等库,而不是编写自己的文件来读取样板代码,您可以摆脱类似的情况:(
上面示例中省略了 IOException 和 ParseException 的处理。)
Using a library such as Guava instead of writing your own file reading boilerplate code, you could get away with something like:
(Handling of IOException and ParseException omitted in above example.)