我正在尝试从文本文件中读取日期,然后将字符串解析为日期,以便我可以将其读入我的数组中。我尝试时不断收到错误消息Date date = sdf.parse (token.nextToken ());
。如何将我从文本文件中读取的字符串转换为日期?
日期设置
void setDate(Date d)
{
date =d;
}
文件阅读器
void read ()
{
SimpleDateFormat sdf = new SimpleDateFormat ("dd/MM/yyyy");
int cnt = 0;
try
{
FileReader fr = new FileReader ("oefeningtaak.txt");
BufferedReader br = new BufferedReader (fr);
boolean canread = true;
while (canread == true)
{
String lyn = br.readLine ();
if (lyn == null)
{
canread = false;
}
else
{
array [cnt] = new Mainobject ();
StringTokenizer token = new StringTokenizer (lyn, "*");
String students = token.nextToken ();
String vak = token.nextToken ();
String maxpunt = token.nextToken ();
String punt = token.nextToken ();
Date date = sdf.parse (token.nextToken ());
array [cnt].setStudents (students);
array [cnt].setVak (vak);
array [cnt].setMaxpunt (Integer.parseInt (maxpunt));
array [cnt].setPunt (Integer.parseInt (punt));
array [cnt].setDate (date);
array [cnt].report ();
cnt++;
}
}
}
catch (IOException err)
{
System.out.println (err.toString ());
}
}
我得到的错误是
方法“java.util.Date parse(java.lang.String $1) throws java.text.ParseException:”可以抛出检查异常“java.text.ParseException”。因此它的调用必须包含在捕获异常的 try 语句中,否则必须声明此方法以抛出异常