Reputation: 53
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
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:
Upvotes: 2
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