簡體   English   中英

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

[英]print a line that contains a specific pattern from a text-file in java

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

一些匹配器會有所幫助,但我不確定它是如何工作的

}}

我上面的那個正在工作,但我還想在文本文件中的任何地方找到一個特定的字符串並打印該行

只需使用 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
            }
        } 
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM