0

私は自分で作成したログを持っており、プログラムで月ごとにログを検索できるようにしたいと考えています。私のfile.txtの形式は次のとおりです。

[31 02/08/13 21:55:47] Name_Surname 0A49G 21

最初の桁は年の週です (私はそれを取得することができ、週ごとに検索できます。月については同じですが、間違っていたようです)、次の 3 つの数字は日です。 /月/年。問題は、配列を分割できないことです (netBeans が「スレッド "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 での例外」と言うため)。問題があると netBeans が指摘する場所に印を付けました。私が欲しいのは、月の数を取得して検索できるようにすることです。

コードは次のとおりです。

    textoMostrado.setText("");
    FileReader fr = null;
    try {
        File file = new File("Registro.txt");
        fr = new FileReader(file);
        if (file.exists()) {
            String line;
            BufferedReader in = new BufferedReader(fr);
            try {
                int mes = Calendar.getInstance().get(Calendar.MONTH);
                mes++;
                int año = Calendar.getInstance().get(Calendar.YEAR);
                año %= 100;
                while ((line = in.readLine()) != null)   {
                    String[] lista = line.split(" ");
                    String [] aux = lista[1].split("/"); //the problem is here
                    int numMes = Integer.parseInt(aux[1]);
                    int numAño = Integer.parseInt(aux[2]);
                    if ((numMes==mes)&&(numAño==año)) {
                        textoMostrado.append(line+"\n"); 
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(MostrarRegistros.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MostrarRegistros.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fr.close();
        } catch (IOException ex) {
            Logger.getLogger(MostrarRegistros.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

私の英語は私の母国語ではありません。誰かが私を助けてくれることを願っています。

4

1 に答える 1

5

この行のペア:

String[] lista = line.split(" ");
String [] aux = lista[1].split("/"); //the problem is here

... 行にスペースが含まれていない場合は常に失敗します。その場合、lista要素は 1 つしかないためです。それを防ぐことができます:

if (lista.length > 1) {
    String[] aux = lista[1].split("/");
    ...
} else {
    // Whatever you want to do with a line which doesn't include a space.
}

私の推測では、サンプルに示されているものとは異なる行がログに含まれていると思いますelse上記の句にログを記録するだけで、簡単に診断できます。ちなみに、空の文字列であることがわかります...

于 2013-08-02T22:03:40.793 に答える