如何使用java从包含特定单词的文件中打印行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21989887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:53:17  来源:igfitidea点击:

How to print lines from a file that contain a specific word using java?

javajava-iofile-handling

提问by D-jay

How to print lines from a file that contain a specific word using java ?

如何使用 java 从包含特定单词的文件中打印行?

Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.

想要创建一个简单的实用程序,允许在文件中查找单词并打印给定单词所在的完整行。

I have done this much to count the occurence but don't knoe hoe to print the line containing it...

我已经做了这么多来计算出现的次数,但不要用锄头来打印包含它的行......

      import java.io.*;

       public class SearchThe {
          public static void main(String args[]) 
           {
             try 
              {
                String stringSearch = "System";

                 BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));

         int linecount = 0;
            String line;

        System.out.println("Searching for " + stringSearch + " in file...");

        while (( line = bf.readLine()) != null)
        {
            linecount++;
            int indexfound = line.indexOf(stringSearch);

            if (indexfound > -1) 
            {
                System.out.println("Word is at position " + indexfound + " on line " + linecount);
            }
        }
        bf.close();
    }
    catch (IOException e) 
    {
        System.out.println("IO Error Occurred: " + e.toString());
    }
}

}

}

采纳答案by user3213851

Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".

假设您正在读取名为 file1.txt 的文件,那么您可以使用以下代码打印包含特定单词的所有行。假设您正在搜索“foo”这个词。

import java.util.*;
import java.io.*;
    public class Classname
    {
        public static void main(String args[])
        {
        File file =new File("file1.txt");
        Scanner in = null;
        try {
            in = new Scanner(file);
            while(in.hasNext())
            {
                String line=in.nextLine();
                if(line.contains("foo"))
                    System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }}

Hope this code helps.

希望这段代码有帮助。

回答by markgiaconia

you'll need to do something like this

你需要做这样的事情

   public void readfile(){
     try {

        BufferedReader br;
        String line;

        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
        br = new BufferedReader(inputStreamReader);
        while ((line = br.readLine()) != null) {
          if (line.contains("the thing I'm looking for")) {
            //do something 
          }
          //or do this
          if(line.matches("some regular expression")){
            //do something
          }
        }

        // Done with the file
        br.close();
        br = null;

      }
      catch (Exception ex) {
        ex.printStackTrace();
      }
  }

回答by Kayz

Have a look at BufferedReaderor Scannerfor reading the file. To check if a String contains a word use containsfrom the String-class.

查看BufferedReaderScanner阅读文件。要检查字符串是否包含contains来自String-class的单词。

If you show some effort I'm willing to help you out more.

如果你表现出一些努力,我愿意帮助你更多。

回答by m-szalik

public static void grep(Reader inReader, String searchFor) throws IOException {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(inReader);
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains(searchFor)) {
                System.out.println(line);
            }
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

Usage:

用法:

   grep(new FileReader("file.txt"), "GrepMe");