public class Auto
{
public static void main(String [] args) {
// The name of the file to open.
System.out.print("\nPlease enter TextfileName.txt : ");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.next();
int counter = 0;
//Reading filename.text from code
System.out.println("\nReading '"+fileName+"' from Java Code.\n");
//Date and time stamp for the program.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.print("Todays date: "+dateFormat.format(date)+"\n\n\n");
// This will reference one line at a time
String line = null;
FileReader fileReader = null;
//-------------------------------------------------------TAB_1----------------------------------------------//
System.out.println("\t\t\t\t TAB_1[Date on]\n");
try {
// FileReader reads text files in the default encoding.
fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 1 || counter == 3 || counter == 9)
{
// print out the lines above that are found in the text
System.out.println(line);
System.out.println("----------");
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
// BufferedReader.close();
}
}
some matcher would help, but i`m not sure how it works
}}
The one i have above is working but i want to also find a specific string anywhere in the text-file and print that line
Just use the contains method of the String class to check for occurances of a substring inside a string.
while((line = bufferedReader.readLine()) != null) {
if (line.contains("some string") {
System.out.println(line);
System.out.println("----------");
}
}
If you wish to check multiple substrings and not just one then you should create a String array of all the substrings you want to look for and loop through them.
First add the following line at the beggining of the class :
public static final String[] listOfStrings = new String[] { "substring 0", "sub string 1" , "substring 2" };
Replace the substrings with your own values.
Then, loop through them to find matches:
while((line = bufferedReader.readLine()) != null) {
for (String match : listOfStrings) {
if (line.contains(match)) {
System.out.println(line);
System.out.println("----------");
break; // No need to continue after the first match
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.