【问题标题】:Java split ignoring white space [closed]Java拆分忽略空格[关闭]
【发布时间】:2018-05-05 08:14:21
【问题描述】:

所以,假设我有这个代码

String some = ("my name|username|password");
String[] split = some.split("|");

我想要这样的字符串

split[0] = "my name";
split[1] = "username";
split[0] = "password";

这是我的代码

String record = null;
FileReader in = null;
MainMenu menu = null;
public void checkLogin() throws FileNotFoundException, IOException, ArrayIndexOutOfBoundsException {
    in = new FileReader("D:\\Login.txt");
    BufferedReader br = new BufferedReader(in);

    String username = txfUsername.getText();
    String password = new String(txfPassword.getPassword());

    while ((record = br.readLine()) != null) {

        String[] split = record.split("-");

        if (username.equals(split[1]) && password.equals(split[2])) {

            JFrame frame = new JFrame();
            menu = new MainMenu(split[0]);
            this.setVisible(false);
            menu.setVisible(true);

            break;
        }
    }

    if (menu == null) {
        JOptionPane.showMessageDialog(null, "Username or Password wrong.");
    }
}

这里是 login.txt

my name-user-pass

当我运行程序时,它会抛出 arrayindexoutofbound 异常 如何摆脱它?

【问题讨论】:

  • 您需要向我们展示异常的完整堆栈跟踪,并告诉我们数组访问发生在程序中的哪些行号。您还需要打印出记录的值,以确保您正确读取它。
  • 在调试器中查看split的值
  • “当我运行程序时,它会抛出ArrayIndexOutOfBoundsException 异常。如何摆脱它?” 在执行split[1] 和@987654330 之前检查split.length @,以确保您有 3 个值。如果您认为应该得到 3 个值,但没有得到 3 个值,则您调试代码以找出未满足您的期望的原因。

标签: java arrays split


【解决方案1】:

在我看来,在处理文本文件时,您要始终确保您实际处理的是数据行,尤其是在您的应用程序不负责创建文本文件的情况下。您还应该始终注意数据行可能不包含所有必需数据的事实,以消除在使用 String.split() 时遇到 ArrayIndexOutOfBoundsException 的可能性强>方法。

您可能还希望允许一种机制来处理文本文件中的注释行,以便可以添加一些注释行。这些行当然会被忽略,空白行也会被忽略。在这种情况下,文本文件路径和文件名在方法中是硬编码的,但如果文件是用户可以通过 JFileChooser(或其他)选择的,那么如果文件的第一行是注释行,指示什么该文件用于,例如:

;MyAppName Login Data

;Real Name, Login Name, Password
John Doe, johnnyboy, cGFzczEyMzQ
Bill Smith, BoperBill, U3VwZXJDb29sMQ
Tracey Johnson, tracey, NzcyMzQ2Ng
Fred Flinstone, PebblesDaddy, V2lsbWEnc19EdWRl 

在上面的示例文件布局中,以分号 (;) 开头的行被视为注释行。第一个注释是文件描述符。读取文件时,会检查此行,如果它说明了预期内容,那么您知道它很可能是要处理的正确文本文件,否则用户提供或选择了错误的文本文件。

您会注意到密码已加密。甚至你也不应该知道它们是什么。密码仅对用户保密。这里使用了一个简单的Base64 Encryption(需要Java 8+),但仅用于示例目的。它可能对某些应用程序来说已经足够了,但绝对不是对所有应用程序都足够好,但是,有总比没有好。

在您的情况下,要在 Base64 中加密密码,您可以使用(import java.util.Base64 必需):

String password = Base64.getEncoder().withoutPadding().
        encodeToString(String.valueOf(txfPassword.
        getPassword()).getBytes());

在将用户密码保存到文件之前执行此操作。

您的 checkLogin() 方法如下所示:

public void checkLogin() throws FileNotFoundException, IOException {
    // Try with Resources...This will auto-close the BufferReader.
    try (BufferedReader br = new BufferedReader(new FileReader("D:\\Login.txt"))) {
        // Install code here to validate that txfUsername and txfPassword 
        // text boxes actually contain something. Exit method if not.
        // ................................

        String userName = txfUsername.getText();
        // Encrypt supplied password and compare to what is in file
        String password = Base64.getEncoder().withoutPadding().encodeToString(String.valueOf(txfPassword.getPassword()).getBytes());

        if (userName.equals("") || password.equals("")) {
            return;
        }

        String line;
        int lineCounter = 0;
        boolean loginSuccess = false;
        while ((line = br.readLine().trim()) != null) {
            lineCounter++;
            // Is this the right data file?
            if (lineCounter == 1 && !line.equals(";MyAppName Login Data")) {
                JOptionPane.showMessageDialog(this, "Wrong Text File Supplied!",
                        "Invalid Data File", JOptionPane.WARNING_MESSAGE);
                return;
            }
            // Skip blank and comment lines...
            if (line.equals("") || line.startsWith(";")) { continue; }

            // Split the comma/space delimited data line (", ")
            String[] lineSplit = line.split(",\\s+"); // \\s+ means 1 or more spaces
            // make sure we have three array elements
            if (lineSplit.length == 3 && userName.equals(lineSplit[1]) && password.equals(lineSplit[2])) {
                loginSuccess = true;
                JFrame frame = new JFrame();
                menu = new MainMenu(lineSplit[0]);
                this.setVisible(false);
                menu.setVisible(true);
                break;
            }
        }
        // Can't find login name or password in file.
        if (!loginSuccess) {
            JOptionPane.showMessageDialog(this, "Invalid User Name or Password!", 
                    "Invalid Login", JOptionPane.WARNING_MESSAGE);
        }
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    相关资源
    最近更新 更多