Goran B
Goran B

Reputation: 53

Finding specific text in txt file and storing it in String

first I want to say that I'm beginer and that this is my first Java program. I'd like to make a program that will read text file, find specific line, and save it to my string variable.

So I want to find line that starts with "Dealt to ", and then in that line, copy everything after that till this char '[' and put it in my string variable.

So let's say that I have this line in my text file: Dealt to My NickName [text] I want to have a program that will find text "My Nickname" and put it in my string variable.

I'm trying to work with classes and trying to use setters and getters just to practice, please let me know how my code looks like and how I can improve it and make it work.

this is Main.java:

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException{
        HandHistory hh1 = new HandHistory();
        String hero1 = null;

        hero1 = hh1.getHero();
        System.out.println(hero1);

    }
}

My HandHistory.java:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HandHistory {

    private String hero; 

    public HandHistory(){}

    public String getHero() throws IOException {
        FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt");
        BufferedReader br = new BufferedReader(in);

        String line;
        while ((line = br.readLine()) != null) {
            if (line.contains("Dealt to ")){
                hero = line.substring(9,(line.indexOf("["))-1);

            }
        }                   
        return hero;
    }

    public void setHero(String hero){
        this.hero = hero;
    }
}

Upvotes: 1

Views: 96

Answers (2)

jhncz
jhncz

Reputation: 163

It's a good start, good way to read a file line by line. The one problem worth fixing is closing the FileReader resource by using a try-finally block, or since Java 7 the new try-with-resources block:

try (FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt")) {
  ...
}

Other tips and comments I can think of:

  • You don't have to have a setter in your class if you don't actually need it
  • Your code doesn't work will if there are lines contain the string "Dealt to" but don't start with that string. E.g. "Foobar Dealt to My NickName [text]" will still be matched but will return a wrong value
  • If you really only want to match lines that start with "Dealt to" then use String.startsWith() instead of String.contains()
  • You should handle the case when there's no "[" in the string, otherwise your code crashes with a hard to understand error
  • Regular expressions are useful if they remove complexity from your code. In your case the problem can be solved by using startsWith and indexOf relatively easily, so I'd not use RegExps in this case
  • It's not obvious what HandHistory.getHero() does without looking at the actual code. It's always very helpful even for yourself to assign names to things that express what the class or method is actually doing.
  • It can be said that getHero() method does too many things and so does the class HandHistory, but that's maybe something to consider when using the code for something bigger than a learning hello-world example.

Upvotes: 2

Leonel Atencio
Leonel Atencio

Reputation: 474

My advise would be to use a Regex. You can try with

(?<=beginningstringname)(.*\n?)(?=endstringname)

So, for your problem this would be

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "Dealt to My NickName [text]";
      String pattern = "(?<=Dealt to )(.*\n?)(?=[)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);

      //m now haves what you desire. You can loop it if you want.
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

Try this tutorial for using regular expressions in Java http://www.tutorialspoint.com/java/java_regular_expressions.htm

Upvotes: 1

Related Questions