Let's say You've edited a little Your txt file:
Return-Path: <example_from@dc.edu>
X-SpamCatcher-Score: 1 [X]
Received: from [136.167.40.119] (HELO dc.edu)
By: fe3.dc.edu (CommuniGate Pro SMTP 4.1.8)
With: ESMTP-TLS id 61258719
For: example_to@mail.dc.edu; Mon, 23 Aug 2004 11:40:10 -0400
Message-ID: <4129F3CA.2020509@dc.edu>
Date: Mon, 23 Aug 2005 11:40:36 -0400
From: Taylor Evans <example_from@dc.edu>
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.0.1) Gecko/2002082Netscape/7.0
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: Jon Smith <example_to@mail.dc.edu>
Subject: Business Development Meeting
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit'
...and You know it's path. Than, You can do simple while
iteration, cooperated with simultaneously checking if currently reading line begins with specific String
value. For example You want to display a line, where it begins with "Subject:" text. In this case, look on the example below and rearrange it for Your needs.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class SearchTxtDemo {
public static void main(String args[]) {
/* declare and initialize reader for reading values from the console */
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
/* prompt text for the user so he/she can decide, value of which tag should be displayed */
System.out.println("Number + ENTER for getting value of specific tag:");
String[] tags = new String[] {"Return-Path [0]", "X-SpamCatcher-Score [1]", "Received [2]",
"By [3]", "With [4]", "For [5]", "Message-ID [6]", "Date [7]", "From [8]", "User-Agent [9]",
"X-Accept-Language [10]", "MIME-Version [11]", "To [12]", "Subject [13]", "Content-Type [14]",
"Content-Transfer-Encoding [15]"};
for (String i : tags) {
System.out.println(i);
}
/* get value given by the user */
int valueGivenByUser = -1;
try {
valueGivenByUser = Integer.parseInt(consoleReader.readLine());
consoleReader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
/* cut the value given by the user by the whitespace, e.g "space" */
String[] searchForTag = tags[valueGivenByUser].split("\\s");
/* declare reader for the file with Your data */
BufferedReader filereader;
try {
/* initialize file reader */
filereader = new BufferedReader(new InputStreamReader(
new FileInputStream("D:/Eclipse Java 8/eclipse_workspace/SampleText/src/SampleText.txt")));
/* read the file in the iteration manner, */
/* until reader will reach the end of the file */
String line;
while ((line = filereader.readLine()) != null) {
/* check if readed line begins with the tag chosen by the user */
/* if it matches, than show whole readed line in the console */
if (line.startsWith(searchForTag[0])) {
System.out.println(line);
break;
}
}
filereader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}