数组超界如何解决

ls8182 2009-08-19 10:24:28
我读的是一个文本,内容是两行数据 aaa|bbb|ccccc|ffff|dddgfg
1|2222|3333333|dfgg|2dgh 执行下面的语句
while ((str = br.readLine()) != null) {
String[] names = str.split("\\|");
String col1=names[0];
String col2=names[1];
String col3=names[2];
String col4=names[3];
String col5=names[4];
if (col5==null){col5="";}
System.out.println(col5);
String sqlinsert = "insert into readfile values ('"+col1+"','"+col2+"','"+col3+"','"+col4+"','"+col5+"')";
ps=connection.prepareStatement(sqlinsert);
ps.execute(sqlinsert);
} 是没有问题的,但是有个新问题,就是如果文本每行里最后一个字符串是空,比如说 第一行aaa|bbb|ccccc|ffff|
第二行1|2222|3333333|dfgg|执行就会报数组超界,数据就不能执行插入操作了,如何解决呢????
...全文
264 11 打赏 收藏 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
jxst051665 2009-08-19
  • 打赏
  • 举报
回复
\\|\\s*(?=$)|\\s*这个里面

(?=$)直接用$ 行不行?我怎么觉得没必要用这种子式
whuisszl008 2009-08-19
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 bigbug9002 的回复:]
Java codewhile ((str= br.readLine())!=null) {
str=str.replaceAll("\\|\\s*(?=$)|\\s*","");
String[] names= str.split("\\|");if(names.length==5){
String sqlinser¡­
[/Quote]
up
根据names.length的大小,做相应的处理。
qqyatou 2009-08-19
  • 打赏
  • 举报
回复
在插入前
最好先判断最后一个字符是不是'|'
如果是就把最后一个'|'去了
然后在做处理
bea_java 2009-08-19
  • 打赏
  • 举报
回复
如果有的话 可以这么做:
在插入之前一定要判断最后是否为NUll主要是因为你的数据跟数据库的数据类型有冲突。
ls8182 2009-08-19
  • 打赏
  • 举报
回复
具体如何做啊,刚试了一下,还不行啊
dm520 2009-08-19
  • 打赏
  • 举报
回复
我认为最好是把最后的|去掉就好了阿
bigbug9002 2009-08-19
  • 打赏
  • 举报
回复
while ((str = br.readLine()) != null) { 
str=str.replaceAll("\\|\\s*(?=$)|\\s*","");
String[] names = str.split("\\|");
if(names.length==5){
String sqlinsert = "insert into readfile values ('"+names[0]+"','"+names[1]+"','"+names[2]+"','"+names[3]+"','"+names[4]+"')";
}else{
//做相应处理;
}
}
lookhang 2009-08-19
  • 打赏
  • 举报
回复
你可以捕获这个异常,然后在catch里面照常插入~
lookhang 2009-08-19
  • 打赏
  • 举报
回复
你可以捕获这个异常,然后在catch里面照常插入~
bigbug9002 2009-08-19
  • 打赏
  • 举报
回复
str=str.replaceAll("\\|\\s*(?=$)|\\s*","");把最后的'|'和多余的空格去掉.
一头头 2009-08-19
  • 打赏
  • 举报
回复
用容器

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧