从java中的文本文件中打印包含特定模式的行

时间:2015-07-29 08:37:54

标签: java matcher

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();            
    }
}

一些匹配者会帮忙,但我不确定它是如何运作的

}}

我上面的那个是工作但我想在文本文件中的任何地方找到一个特定的字符串并打印该行

1 个答案:

答案 0 :(得分:0)

只需使用String类的contains方法来检查字符串中子字符串的出现。

while((line = bufferedReader.readLine()) != null) {
        if (line.contains("some string") {
           System.out.println(line);
           System.out.println("----------");
        }
    }   

如果你想检查多个子串而不只是一个子串,那么你应该创建一个包含你想要查找的所有子串的String数组并循环遍历它们。

首先在类的开头添加以下行:

public static final String[] listOfStrings = new String[] { "substring 0", "sub string 1" , "substring 2" }; 

用您自己的值替换子字符串。

然后,遍历它们以找到匹配项:

   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
            }
        } 
    }