Reputation: 53
so i have the code
public void reply(){
String fileName = "readLog.txt";
String line = null;
try {
FileReader fileReader =
new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
Output.append(line);//output is name of textarea
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}
and it reads out what is in the text file fine but I want it to read say line 1, and in line 1 I would have something like:
A Question - A answer
and I want it so It can place the lines in the correct places e.g
if("Input" == "A Question") { somethinghappends(); }
I know thats not how you would set out a if statment with strings it is just an example.
how would I go about doing this? (ive looked around the internet and haven't found much of use)
Upvotes: 0
Views: 4247
Reputation: 8853
You can use the bufferedreader.readline()
method to read from the stream until you find your desired line. Get the data and process on it. You might use the equals()
method for comparison. You can finally part your string using split()
and store it in array.
Upvotes: 0
Reputation: 900
So you have a question String and want to find the fitting answer in readLog.
The best way would be splitting your answers at " - ". (A better seperator would be "\t" since " - " could also be a part of the question/answer.)
String q="question";
String qa="question - answer";
String[] split = qa.split(" - ");
if(split[0].equals(q)){
do something;
}
Upvotes: 1
Reputation: 8846
You can use String.split():
while((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("-");
if (parts.length >= 2 && parts[0].trim().equals(parts[1].trim())) {
doSomethingHere();
}
}
I also use String.trim() to remove leading and trailing spaces around the question and the answer before comparing them.
Upvotes: 1
Reputation: 1083
If your format is:
A question - An answer,
You can do something like:
String[] parts = line.split(" - ");
String question = parts[0];
String answer = parts[1];
Considering that the dash is the separator. This one is in the loop that reads every line.
Upvotes: 2