编写程序查找搜索命令行中指定的所有文件并打印出包含指定单词的所有行

时间:2013-04-23 12:30:35

标签: java

编写程序查找搜索命令行中指定的所有文件并打印出包含指定单词的所有行。例如,如果你打电话

java Find ring report.txt addres.txt Homework.java

然后程序可能会打印

report.txt: has broken up an international ring of DVD bootleggers that
address.txt: Kris Kringle, North Pole
address.txt: Homer Simpson, Springfiled
Homework.java: String filename

首先,我无法弄清楚如何存储命令行中给出的所有字符串。此外,我的代码只在找到的单词之后打印行的部分(因此,对于inst6ance,它只打印出来:第一个文件的DVD盗版者。我怎么能解决这些问题?有人可以帮忙吗?我吗?

这是我的尝试:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class P6 {

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub


        for (int i = 0; i<args.length; i++)
        {
            String arg = args[i];
        }

        String input = "ring";

        File one = new File("report.txt");
        Scanner in = new Scanner(one);
        while (in.hasNext())
        {
            String een = in.next();

            if(een.matches(input))
            {
                System.out.println(in.nextLine());
            }
        }

    }

}

2 个答案:

答案 0 :(得分:1)

public static void main(String[] args) throws FileNotFoundException {
    String input = args[0];
    for (int i = 1; i < args.length; i++) {
        System.out.println(" File  " + args[i]);
        File one = new File(args[i]);
        Scanner in = new Scanner(one);
        while (in.hasNext()) {
            String line = in.nextLine();
            if (line.contains(input)) {
                System.out.println(line);
            }
        }
    }
}

答案 1 :(得分:0)

试试这个:

File one = new File("try.txt");
    Scanner in = new Scanner(one);
    String input = "jha";
    while (in.hasNextLine()) {
        String een = in.nextLine();

        if (een.contains(input)) {
            System.out.println(een);
        }
    }