我面临几天前遇到的问题。我必须解析此文件并将字符串转换为日期。我几天前对另一个CSV文件做了同样的事情。但是,新文件出现此错误:java.text.ParseException:Unparseable date:“”3/4/2011“”
为什么字符串会在其周围打印两个“”?我认为这是问题的根本原因。我发布下面的代码。请注意,相同的代码适用于另一个文件,其中日期打印为3/4/2011,周围没有“”。
WritableWorkbook wbwrite=null;
WritableSheet sheet=null;
Label lwrite=null;
BufferedReader br=null;
Number n=null;
String strFile="quotes.csv";
String strLine = "";
String st[];
String delimiter="[,]";
int lineNumber = 0, tokenNumber = 0;
int length=0;
int counter=0;
Calendar cal = Calendar.getInstance();
DateTime datecell=null;
if(strFile.equals("quotes.csv"))
{
System.out.print("in loop if");
try
{
File file=new File("quotes.xls");
wbwrite=Workbook.createWorkbook(file);
System.out.print("file created");
//path=file.getCanonicalPath();
sheet = wbwrite.createSheet("Sheet 1", 0);
lwrite=null;
n=null;
Date dtest=null;
DateFormat df=null;
Date dadd=null;
df=new SimpleDateFormat("dd-mm-yy");
//create BufferedReader to read csv file
br = new BufferedReader( new FileReader(strFile));
strLine = "";
//st[]=empty;
delimiter="[,]";
lineNumber = 0; tokenNumber = 0;
length=0;
//read comma separated file line by line
while( (strLine = br.readLine()) != null)
{
//System.out.print("strline="+strLine);
//break comma separated line using ","
st=strLine.split(delimiter);
length=0;
while(length<st.length)
{
//display csv values
//
System.out.println("Line # " + lineNumber +
", Token # " + tokenNumber
+ ", Token : "+ st[length]);
if(tokenNumber==2)
{
System.out.print("date="+st[length]);
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(st[length]);
System.out.print("date="+date);
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 17);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
System.out.print("date="+date);
datecell=new DateTime(tokenNumber,lineNumber,date);
sheet.addCell(datecell);
lwrite=new Label(tokenNumber,lineNumber,st[length]);
sheet.addCell(lwrite);
}
if(tokenNumber==1||tokenNumber==5||tokenNumber==6||tokenNumber==7)
{
n=new Number(tokenNumber,lineNumber,Float.parseFloat(st[length]));
sheet.addCell(n);
}
tokenNumber++;
length++;
}
//reset token number
//tokenNumber = 0;
}
wbwrite.write();
wbwrite.close();
}
catch(Exception e)
{
System.out.print("error="+e);
}
}
}
答案 0 :(得分:0)
我解决了。该字符串已经有前导和尾随引号,在解析时会产生双引号。这就是为什么“”2011年3月4日“”。 我添加了
if (st[length].startsWith("\""))
{
st[length] = st[length].substring(1, st[length].length());
}
if (st[length].endsWith("\""))
{
st[length] = st[length].substring(0, st[length].length() - 1);
}
加上即使是日期格式也是dd-MM-yyyy;改为dd / MM / yyyy。现在我得到了正确的答案。