使用拆分搜索文件

时间:2018-06-19 16:57:10

标签: java android file

我有一个users1.txt,其中有一些注册表,例如:basketball president tom@gmail.com 1234,并且我正在让用户输入电子邮件,密码和两种Spinner选项作为输入,我想在文件中搜索它们并进行比较他们,如果它是真的,我会打印一条消息(open()函数)。在下面的代码中,条件已成功完成,但仅针对文件的第一行,我要检查用户每次输入的所有文件。更具体地说,我希望搜索不停止到basketball president tom@gmail.com 1234,而是继续到第二行football referee tam@gmail.com 123123等,直到文件结尾。任何建议都会很棒。

signBtn.setOnClickListener(new View.OnClickListener() {
        @Override
     public void onClick(View view) {

                if( TextUtils.isEmpty(email.getText()))
                    email.setError("Email Required");

               else if( TextUtils.isEmpty(password.getText()))
                    password.setError("Password Required");

               else {


                   String text = readFromFile("users1.txt");
                        String[] splited = text.split("\\s+");


   if(SportSpinner.getSelectedItem().toString().equals(splited[0]) && (UserSpinner.getSelectedItem().toString().equals(splited[1])) && (password.getText().toString().equals(splited[3])) && (email.getText().toString().equals(splited[2])))
         open(SportSpinner.getSelectedItem().toString(), UserSpinner.getSelectedItem().toString());
                      else
                      {
                          if(tries==1)
                              open();

                       signBtn.startAnimation(shakeAnimation);
                       tries--;
                       message(tries);
                      }

                }

            }
        });

    }

    private String readFromFile(String name){
    StringBuilder text = new StringBuilder();
        try {
            File file = new File(getFilesDir().getAbsolutePath(),name);
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
            br.close();
        }catch(IOException e){
            Log.e("Exception", "File read failed: " + e.toString());
        }
        return String.valueOf(text);
    }

1 个答案:

答案 0 :(得分:0)

如果文件中的行始终是相同编号的集合,则可以使用循环来增加所检查的索引。如果找到它,我还会添加某种标记以停止搜索。

    boolean found = false;
    for (int i = 0; i <= splitted.length-3 && !found; i += 4) {
        if(SportSpinner.getSelectedItem().toString().equals(splited[i]) && (UserSpinner.getSelectedItem().toString().equals(splited[i+1])) && (password.getText().toString().equals(splited[i+3])) && (email.getText().toString().equals(splited[i+2]))) {
        found = true;

        // Your open method goes here
        }
    }
    if (!found) {
    // Now put all the code from the previous else statement here, since it has now searched the whole list for the one set of inputs
    }

这将检查文件的每一行是否匹配,如果匹配则退出循环。