简体   繁体   中英

Comparing txt file with input String in Android

I have created a txt file and saved it in the file Explorer at data/data/com.xxx/files/mynote/txt when I entered a string into edit text and click the button.

I want compare txt file content and input String. In my txt file, only minimum length 5 to 6 is stored. How do I do this? I have tried but it can not compare properly - it goes to else block part when I entered the same string as i save in my txt file like "tazin".

Here is my code.

  btnSubmitCode=(Button)findViewById(R.id.button_Submit);
        btnSubmitCode.setOnClickListener(new OnClickListener() {

        @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

            if(editText_Code.getText().toString().isEmpty()) 
                {
                    Toast.makeText(getApplicationContext(),"Please Enter Code", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    String strCode = editText_Code.getText().toString().trim();
                    create_File(strCode);
                    readFile();
                }

                String temp;
                String searchString = "tazin";

                try {
                    File file=new File("/data/data/com.xxxxx/files/mynote.txt/");

                    BufferedReader in = new BufferedReader(new FileReader(file));
                    while (in.readLine() != null)
                    {
                        temp = in.readLine();
                        System.out.println("String from txt file ="+temp);
                        if(searchString.equals(temp))
                        {
                            System.out.println("word is match");
                            in.close();
                            return;
                        }
                        else
                        {
                            System.out.println("word is not match");
                        }
                    }
                    in.close();

                } 

                 catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });




//Write File
    private void create_File(String strtext)
    {
        FileOutputStream fos = null;
        try
        {
            fos = openFileOutput("mynote.txt", MODE_PRIVATE);
            fos.write(strtext.getBytes());
            Toast.makeText(getApplicationContext(), "File created succesfully",
                    Toast.LENGTH_SHORT).show();

        }
        catch(FileNotFoundException fexception)
        {
            fexception.printStackTrace();

        }
        catch(IOException ioexception)
        {
            ioexception.printStackTrace();
        }

        finally
        {
            if (fos != null) 
            {
                try 
                {
                    // drain the stream
                    fos.flush();
                    fos.close();
                }
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }


    //Read File

    private void readFile()
    {


        FileInputStream fis;

        try 
        {
            fis = openFileInput("mynote.txt");
            byte[] reader = new byte[fis.available()];
            while (fis.read(reader) != -1) 
            {

            }


            textView_ReadCode.setText(new String(reader));
            strReadFile = new String(reader);
            System.out.println("Read File Into String Format " + strReadFile);


            Toast.makeText(getApplicationContext(), "File read succesfully",
                    Toast.LENGTH_SHORT).show();

            if (fis != null)
            {
                fis.close();
            }
        } 
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            Log.e("Read File", e.getLocalizedMessage());
        }

    }

You're misusing the BufferedReader.readLine() method. You're calling it twice each time through your while loop; once in the while conditional, and once in the loop block itself. So, when you do temp = in.readLine() and then the searchString.equals(temp) comparison, you've already skipped a line from the text file. Structure your loop like so:

temp = in.readLine();
while (temp != null)
{
    System.out.println("String from txt file =" + temp);

if(searchString.equals(temp))
{
        System.out.println("word is match");
        in.close();
        return;
    }
    else
    {
        System.out.println("word is not match");
    }

    temp = in.readLine();
}

Edit:

Per our chat in comments, here is the updated code for what you need:

btnSubmitCode.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View arg0)
        {
            String str = editText_Code.getText().toString();

            if(str == null || str.equals(""))
            {
                Toast.makeText(getApplicationContext(), "Please Enter Code", Toast.LENGTH_SHORT).show();
            }
            else
            {
                String strCode = str.trim();
                if(checkCode(strCode))
                {
                    System.out.println("word is match");   
                }
                else
                {
                    System.out.println("word is not match");                    
                }
            }
        }
    }
);
...
...

// Returns true if the code has already been used
// Returns false if the code is new
// Creates mynote.txt if it doesn't exist
// Appends code if it is new
private boolean checkCode(String code)
{
    String temp;
    File file = new File(getFilesDir() + "mynote.txt");

    if(file.exists())
    {
        try
        {
            BufferedReader in = new BufferedReader(new FileReader(file));
            temp = in.readLine();
            while (temp != null)
            {
                if(code.equals(temp))
                {
                    // Match was found
                    // Clean up and return true
                    in.close();
                    return true;
                }

                temp = in.readLine();
            }
            in.close();
        }
        catch (FileNotFoundException e)
        {

        }
        catch (IOException e)
        {

        }

    }

    // Match was not found or File doesn't exist
    // Append code to mynote.txt and return false
    try
    {
        BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
        out.newLine();
        out.write(code);
        out.close();
    }
    catch (IOException e)
    {

    }

    return false;
}

在您的问题中,您编写了不同的路径,然后在代码中编写了代码,因此只需检查文件路径即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM