1

次のようにフォーマットされたファイルから情報を抽出しようとしています。

1
test@mail.ca|password|false

ただし、ArrayIndexOutOfBounds次のコードを実行するとエラーが発生するようで、分割が正しく機能していると思われるため、その理由を特定できません。「users」で始まる行でエラーが取得されます。

        sc = new Scanner (System.in);
        BufferedReader in = new BufferedReader (new FileReader (USAVE));
        int repeats = Integer.parseInt(in.readLine());
        for (int c = 0; c < repeats; c++){
            String info = in.readLine();
            System.out.println (info);
            String[] extracted = info.split("\\|");
            users.addUser(extracted[0], decryptPassword(extracted[1]));
        }
        in.close();

何が問題なのですか?

編集:「|」を変更しました 「\|」に しかし、問題は解決しません。

EDIT2:スタックトレース

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at OnlineCommunications.userFromFile(OnlineCommunications.java:165)
at OnlineCommunications.logIn(OnlineCommunications.java:36)
at OnlineCommunications.emailOption(OnlineCommunications.java:593)
at OnlineCommunications.main(OnlineCommunications.java:683)

上に投稿したメソッドは、 という名前のメソッドですuserFromFile

4

4 に答える 4

6

String#split(regex)は、パラメーターとして正規表現を想定しており|、正規表現の世界ではメタ文字 (特殊文字) です。メタ文字を通常の文字として扱うには、バックスラッシュ (\|) でエスケープする必要があります。

String[] extracted = info.split("\\|");

または、文字クラス内に含めるだけです

String[] extracted = info.split("[|]");

以下は、正規表現のメタ文字です。

<([{\^-=$!|]})?*+.>
于 2013-02-28T23:40:17.100 に答える
2

String.split(String regex)正規表現を引数として取り、次を使用します。

String[] extracted = info.split("\\|");
于 2013-02-28T23:40:59.477 に答える
1

同様の投稿。トークン化エラー: java.util.regex.PatternSyntaxException、ぶら下がっているメタ文字 '*'次のように使用する必要があります:

String[] extracted = info.split("\\|");
于 2013-02-28T23:42:31.350 に答える
0

Actually there is nothing wrong with how you are parsing the string. The error lies elsewhere. I would add System.out.println (repeats) just before you enter the loop to make sure you are iterating the correct number of times. To debug even further, I would print the contents of extracted (Arrays.toString(extracted)) before the line invoking user.addUsers. If all that looks good, then the problem lies in the user.addUsers invocation.

于 2013-03-01T00:33:45.797 に答える