有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重试打开目录中的文件

我正在尝试使用以下代码打开某个目录中的文件。文件名按日期分配,但缺少一些日期。我希望遍历日期以获取文件,并使代码在每次找不到文件时返回1天,直到最终找到一个文件(currentdate是一个全局变量,奇怪的xml元素是因为我在使用处理)

我认为代码应该做的是:

  1. 尝试打开具有给定日期的文件
  2. 出现错误时,它将捕获并获取新日期
  3. 重复该过程,直到找到有效日期
  4. 当找到有效日期时,它会转到break所在的行并退出循环

但出于某种原因,它会做一些奇怪的事情,比如编辑,有时会跳得太多,尤其是在第一个月的时候# 我的逻辑是不是因为某种原因不起作用? 谢谢

String strdate=getdatestring(counter);
int counter=0;
while(true){
      try{
        xmldata = new XMLElement(this, "dir/" + strdate + "_filename.xml" ); 
        break;
      }catch(NullPointerException e){
        counter +=1;
        strdate=getdatestring(counter);
      }}

String getdatestring(int counter) {
Date firstdate=new Date();
int daystosum=0;
String strcurrentdate="";

if(keyPressed && key=='7'){
  daystosum=-7;
}
daystosum=daystosum-counter;

Calendar c=Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

try{
firstdate=formatter.parse("2012-04-13");//first day of the database
}catch(ParseException e){
  println(e);
}
c.setTime(currentdate);
c.add(Calendar.DATE,daystosum);
currentdate=c.getTime();
if(currentdate.before(firstdate)){
  currentdate=firstdate;
}
strcurrentdate=formatter.format(currentdate);

return strcurrentdate;
}

共 (1) 个答案

  1. # 1 楼答案

    我相信一旦你这么做了

              daystosum=daystosum-counter;
    

    您需要根据需要重置计数器

              counter = 0;
    

    否则下一次它将减去更大的数字,例如,开始,例如daystosum是0,counter是5,在daystosum=daystosum-counter;之后,daystosum将变成-5。再次进入while循环,但未找到文件,则计数将增加到6。在这种情况下,您将得到`daystosum=daystosum-counter;作为-5-6 = -11,但您希望它移动到-6。重置计数器将解决您的问题

    另一方面,我认为您可以使用父目录中的file.listFiles()列出文件,并对文件名执行搜索。在这种情况下,您不会尝试一次又一次地打开文件