[SOLVED] How to search a text file?! Please help!

I would like to search a simple text file: for instance let’s see the following is the contents of my text file…

Edward Password123
Cedrick pASSWORD321

How do I parse this so that I give my scanner object a username and it finds the respective password? Each username and password are on seperate lines all will be divided by a " " ( a space). How do I go about doing such a thing?

Here’s what I have so far…

package test;

import java.io.*;
import java.util.*;

public class TestFileReader 
{
    public void readFile(String fileName)
    {
        try
        {
            File file = new File(fileName);
            Scanner scan = new Scanner(file);
            
            while (scan.hasNextLine())
            {
                System.out.println(scan.nextLine());
            }
        } catch (FileNotFoundException e) { System.out.println("File not found."); }
    }

    public void writeToFile(String fileName, String Username, String Password)
    {
        try
        {
            FileWriter writer = new FileWriter(fileName, true);
            writer.write("\n" + Username + " " + Password);
            writer.flush();
        } catch (IOException e) {}
    }
    
    public void getPassword(String fileName, String Username)
    {
        try
        {
            File file = new File(fileName);
            Scanner scan = new Scanner(file);
            
        } catch (FileNotFoundException e) { System.out.println("File not found."); }
        
    }
}

If you’re already reading the file line-by-line, you can use a string tokenizer to separate the username and password:

 StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }

Output:

this
is
a
test

Just replace “this is a test” with the nextline read and you can parse out the username and password to do individual checks on them.

Really what I want to do is to have something that when it’s given a username it finds that username’s password…
I don’t really need to separate everything out like that.

Ok… I figured it out…

package test;

import java.io.*;
import java.util.*;

public class TestFileReader 
{
    static String getPassword( String userName )
    {
        try
        {
            BufferedReader r = new BufferedReader( new FileReader("file"));
            String line = null;
            
            while ((line = r.readLine()) != null)
            {
                String[] pair = line.split(" +");
                
                if (pair[0].equalsIgnoreCase(userName))
                {
                    r.close();
                    return pair[1];
                }
            }
            return null;
        } catch (IOException e) { throw new RuntimeException( e ); }
    }
}