0

次のコードを使用して、特定のディレクトリにあるファイルを開こうとしています。ファイルの名前は日付で割り当てられていますが、一部の日付が欠落しています。日付を繰り返してファイルを取得し、ファイルが見つからないたびにコードを1日に戻して、最終的にファイルが見つかるまで続けたい(currentdateグローバル変数であり、奇妙なxml要素は処理を使用しているため) 。

私がコードがすべきだと思うことは次のとおりです。

  1. 指定された日付でファイルを開こうとします。
  2. エラーが発生すると、キャッチして新しい日付を取得します。
  3. 有効な日付が見つかるまで、このプロセスが繰り返されます。
  4. 有効な日付が見つかると、breakisの行に移動し、ループを終了します。

しかし、何らかの理由で、EDITのような奇妙なことをします#特に最初の月の近くでジャンプしすぎることがあります#私のロジックは何らかの理由で機能していませんか?ありがとう

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;
}
4

1 に答える 1

1

あなたがこれをしたら、私は信じます、

          daystosum=daystosum-counter;

カウンターをリセットする必要があります

          counter = 0;

それ以外の場合、次回はさらに大きな数を減算します。たとえば、開始する場合、たとえばdaystosum0とcounter5の場合、daystosum=daystosum-counter;は。daystosumになり-5ます。ここでも、whileループに入り、ファイルが見つからない場合、カウントは6に増加します。その場合、として取得`daystosum=daystosum-counter;され-5-6 = -11ますが、に移動する必要があります-6。カウンターをリセットすると、問題が解決するはずです。

一方、file.listFiles()親ディレクトリからを使用してファイルを一覧表示し、ファイル名を検索できると思います。その場合、ファイルを何度も開こうとはしていません。

于 2012-10-21T23:46:36.070 に答える