Results 1 to 12 of 12
  1. #1
    krechlich is offline Member
    Join Date
    Mar 2011
    Posts
    16
    Rep Power
    0

    Cool How to find specific text from .txt file

    Okay, so i have this problem that i need to find specific word from .txt file. Lets say that i have AddressBook.txt file and i need to find word "username" from it. How can this be done? Thanks in advance :)

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    6

  3. #3
    aadem is offline Member
    Join Date
    Mar 2011
    Posts
    22
    Rep Power
    0

    Default Well

    The way i would do it is first, tokenize the entire txt file into a String one at a time using a for loop. (Scanner has some tools in it to tokenize i believe, and by tokenize i mean split it up word by word)

    Than have a count integer such as ....count++ every time a token matches the word your looking for. That way you can not only find the word in the file, but if its in there more than 1 time. You need to research the best method of doing this in the API, Scanner may not be the most efficient way i for one am still finding things every day in the api

  4. #4
    krechlich is offline Member
    Join Date
    Mar 2011
    Posts
    16
    Rep Power
    0

    Thumbs up

    Well, i really am so new at this so if you could tell me code somehow? My programs code is like this

    Java Code:
    registerB.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
    
                    try {
                        String usernameGetText = usernameTxt.getText();
                        String passwordGetText = passwordTxt.getText();
                        s = new Scanner(new BufferedReader(new FileReader("AddressBook.txt")));
    
                        if (usernameGetText.contains(" ")) {
                            System.out.println("Username cannot contain space!" + newLine);
                            JOptionPane.showMessageDialog(null, "Username cannot contain space!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (passwordGetText.contains(" ")) {
                            System.out.println("Password cannot contain space!" + newLine);
                            JOptionPane.showMessageDialog(null, "Password cannot contain space!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else {
                            FileWriter logOut = new FileWriter(new File("AddressBook.txt"), true);
                            BufferedWriter logBuff = new BufferedWriter(logOut);
                            logBuff.write(newLine + "Username: " + usernameGetText + newLine + "Password: " + passwordGetText + newLine + newLine);
                            logBuff.close();
                            System.out.println("Account succesfully created!!" + newLine);
                        }
    
                    } catch (IOException error) {
                        System.out.println("Error accessing file!" + newLine);
                        JOptionPane.showMessageDialog(null, "Error accessing file!");
                    }
                }
            });
    So i would like to add an else if there that does, if the text field (usernameGetText) contains the same word that is in the .txt file, then it example: popups messagebox, as in other if elses

  5. #5
    sanjeevtarar's Avatar
    sanjeevtarar is offline Senior Member
    Join Date
    Apr 2008
    Location
    Jaipur(India)
    Posts
    318
    Rep Power
    7

    Default

    Please use the below method to check with file

    public boolean compareInFile(String inputWord){

    String word = "";

    File file = new File("C://ReadString.txt");
    try
    {
    Scanner input = new Scanner(file);
    while(input.hasNext()) {
    word = input.next();
    if(inputWord.equals(word))
    return false;
    }

    }catch(Exception error)
    {}
    return true;
    }

    and call this method in if else(compareInFile(usernameGetText))

    Let me know in case of any clarification
    sanjeev,संजीव

  6. #6
    krechlich is offline Member
    Join Date
    Mar 2011
    Posts
    16
    Rep Power
    0

    Default

    Okay thanks for the code, but when i add that "else if (compareInFile(usernameGetText))" it gives error and the error says "non-static method compareInFile(java.lang.String) cannot be referenced from a static context". So how do i fix this? Thanks so much for trying to help me mate :)

  7. #7
    sanjeevtarar's Avatar
    sanjeevtarar is offline Senior Member
    Join Date
    Apr 2008
    Location
    Jaipur(India)
    Posts
    318
    Rep Power
    7

    Default

    change the method signature to:

    public static boolean compareInFile(String inputWord){
    sanjeev,संजीव

  8. #8
    krechlich is offline Member
    Join Date
    Mar 2011
    Posts
    16
    Rep Power
    0

    Default

    Okay i did that and the error went away, but now when i start the program and whatever i write, it always says "Username already exists!" (I made it to say that in the output if username already exists in .txt file) Shortly, program thinks always that the .txt file contains the word usernameGetText, although .txt file really doesn't include that kind of word

  9. #9
    sanjeevtarar's Avatar
    sanjeevtarar is offline Senior Member
    Join Date
    Apr 2008
    Location
    Jaipur(India)
    Posts
    318
    Rep Power
    7

    Default

    Ok

    What is the data inside text file and what is the value of parameter that you are passing in that method

    post your complete code and text file data
    sanjeev,संजीव

  10. #10
    krechlich is offline Member
    Join Date
    Mar 2011
    Posts
    16
    Rep Power
    0

    Default

    No i'm not getting any error's, the code is here:

    Java Code:
    package login;
    
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.*;
    import java.util.Scanner;
    
    public class Main {
    
        private static void createAndShowGUI() {
            final String newLine = System.getProperty("line.separator");
    
    //Create AddressBook
            File AccountBook = new File("AddressBook.txt");
            boolean regExists = false;
            regExists = AccountBook.exists();
            try {
                System.out.println("Creating address book...");
                if (regExists != true) {
                    FileWriter fOut = new FileWriter(AccountBook);
                    BufferedWriter fileOut = new BufferedWriter(fOut);
                    String AccountBookBan = "Accounts" + newLine + newLine;
                    fileOut.write(AccountBookBan);
                    fileOut.close();
                    System.out.println("Address book created!" + newLine);
                } else {
                    System.out.println("Address book was not created, because it already exists!" + newLine);
                }
            } catch (IOException error) {
                System.out.println("Error creating address book!" + newLine);
                JOptionPane.showMessageDialog(null, "Error creating address book!");
            }
    
    
    //Program layout
            JFrame mainFr = new JFrame();
            mainFr.setTitle("User Login");
            mainFr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            int windowWidth = 380;
            int windowHeight = 200;
            Point centP = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
    
            Container cPane = mainFr.getContentPane();
    
            JButton loginB = new JButton("Login");
            JButton registerB = new JButton("Register");
            JButton cancelB = new JButton("Cancel");
            JPanel buttonPanel = new JPanel();
            FlowLayout bpLayout = new FlowLayout();
            buttonPanel.setLayout(bpLayout);
            bpLayout.setHgap(35);
            buttonPanel.add(loginB);
            buttonPanel.add(registerB);
            buttonPanel.add(cancelB);
            cPane.add(buttonPanel, BorderLayout.PAGE_END);
    
            JLabel banLab = new JLabel("Enter login/pass or click register");
            JPanel banPanel = new JPanel();
            banPanel.add(banLab);
            cPane.add(banPanel, BorderLayout.PAGE_START);
    
            JLabel usernameLab = new JLabel("Username");
            JLabel passwordLab = new JLabel("Password");
            final JTextField usernameTxt = new JTextField("", 12);
            final JTextField passwordTxt = new JTextField("", 12);
            JPanel fieldPane = new JPanel();
            fieldPane.setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = 0;
            c.anchor = GridBagConstraints.CENTER;
            c.insets = new Insets(10, 10, 10, 30);
            fieldPane.add(usernameLab, c);
            c.gridx = 1;
            c.gridy = 0;
            c.anchor = GridBagConstraints.CENTER;
            c.insets = new Insets(10, 30, 10, 10);
            fieldPane.add(usernameTxt, c);
            c.gridx = 0;
            c.gridy = 1;
            c.anchor = GridBagConstraints.CENTER;
            c.insets = new Insets(10, 10, 10, 30);
            fieldPane.add(passwordLab, c);
            c.gridx = 1;
            c.gridy = 1;
            c.anchor = GridBagConstraints.CENTER;
            c.insets = new Insets(10, 30, 10, 10);
            fieldPane.add(passwordTxt, c);
            cPane.add(fieldPane, BorderLayout.CENTER);
    
    //Register
            registerB.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Registering...");
                    Scanner s = null;
    
                    try {
                        String usernameGetText = usernameTxt.getText();
                        String passwordGetText = passwordTxt.getText();
                        s = new Scanner(new BufferedReader(new FileReader("AddressBook.txt")));
    
                        if (usernameGetText.contains(" ")) {
                            System.out.println("Username cannot contain space!" + newLine);
                            JOptionPane.showMessageDialog(null, "Username cannot contain space!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (passwordGetText.contains(" ")) {
                            System.out.println("Password cannot contain space!" + newLine);
                            JOptionPane.showMessageDialog(null, "Password cannot contain space!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (usernameGetText.isEmpty()) {
                            System.out.println("You must fill username field! (Minimum of 4 characters)" + newLine);
                            JOptionPane.showMessageDialog(null, "You must fill username field! (Minimum of 4 characters)");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (passwordGetText.isEmpty()) {
                            System.out.println("You must fill password field! (Minimum of 4 characters)" + newLine);
                            JOptionPane.showMessageDialog(null, "You must fill password field! (Minimum of 4 characters)");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (usernameGetText.length() < 4) {
                            System.out.println("Username must be atleast 4 characters long!" + newLine);
                            JOptionPane.showMessageDialog(null, "Username must be atleast 4 characters long!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (passwordGetText.length() < 4) {
                            System.out.println("Password must be atleast 4 characters long!" + newLine);
                            JOptionPane.showMessageDialog(null, "Password must be atleast 4 characters long!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (usernameGetText.equals(passwordGetText)) {
                            System.out.println("Username and password cannot be the same!" + newLine);
                            JOptionPane.showMessageDialog(null, "Username and password cannot be the same!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else if (compareInFile(usernameGetText)) {
                            System.out.println("Username already exists!" + newLine);
                            JOptionPane.showMessageDialog(null, "Username already exists!");
                            usernameTxt.setText("");
                            passwordTxt.setText("");
                        } else {
                            FileWriter logOut = new FileWriter(new File("AddressBook.txt"), true);
                            BufferedWriter logBuff = new BufferedWriter(logOut);
                            logBuff.write(newLine + "Username: " + usernameGetText + newLine + "Password: " + passwordGetText + newLine + newLine);
                            logBuff.close();
                            System.out.println("Account succesfully created!!" + newLine);
                        }
    
                    } catch (IOException error) {
                        System.out.println("Error accessing file!" + newLine);
                        JOptionPane.showMessageDialog(null, "Error accessing file!");
                    }
                }
            });
    
    //Cancel
            cancelB.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Closing...");
                    System.out.println("Closed!" + newLine);
                    System.exit(0);
                }
            });
    
    //Login
            loginB.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Logging in...");
                }
            });
    
    
    //Place and size Window
            mainFr.setBounds(centP.x - windowWidth / 2, centP.y - windowHeight / 2, windowWidth, windowHeight);
            mainFr.setVisible(true);
        }
    
        public static boolean compareInFile(String inputWord) {
    
            String word = "";
    
            File file = new File("AddressBook.txt");
            try {
                Scanner input = new Scanner(file);
                while (input.hasNext()) {
                    word = input.next();
                    if (inputWord.equals(word)) {
                        return false;
                    }
                }
    
            } catch (Exception error) {
            }
            return true;
        }
    
        public static void main(String[] argv) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    The AddressBook.txt file is in the same folder as the program and the txt file contains only word "Accounts", but it will contain the account information after the account is registered with the program
    Last edited by krechlich; 03-17-2011 at 03:01 PM.

  11. #11
    sanjeevtarar's Avatar
    sanjeevtarar is offline Senior Member
    Join Date
    Apr 2008
    Location
    Jaipur(India)
    Posts
    318
    Rep Power
    7

    Default

    Oh!!!!!

    By mistake we checked wrong condition, please change in compareInFile method the return value like below

    Java Code:
        public static boolean compareInFile(String inputWord) {
    
            String word = "";
    
            File file = new File("AddressBook.txt");
            try {
                Scanner input = new Scanner(file);
                while (input.hasNext()) {
                    word = input.next();
                    if (inputWord.equals(word)) {
                        return [B]true[/B];
                    }
                }
    
            } catch (Exception error) {
            }
            return [B]false[/B];
        }

    If your problem is solved then please mark this as Solved
    sanjeev,संजीव

  12. #12
    krechlich is offline Member
    Join Date
    Mar 2011
    Posts
    16
    Rep Power
    0

Similar Threads

  1. Find and Replace in Text File
    By hamidsharifi in forum New To Java
    Replies: 2
    Last Post: 02-13-2011, 02:01 AM
  2. Reading specific portions of text file
    By Plex in forum New To Java
    Replies: 1
    Last Post: 11-09-2010, 06:45 PM
  3. writing to specific line in text file
    By mickmos in forum New To Java
    Replies: 2
    Last Post: 04-18-2009, 01:01 PM
  4. Writing To A Specific Text File Line
    By mokonji in forum New To Java
    Replies: 1
    Last Post: 03-02-2009, 08:13 PM
  5. find and replace text from a text file
    By gezzel in forum New To Java
    Replies: 2
    Last Post: 09-19-2008, 04:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •