如何使用Java搜索JSON文件中的任何单词



我的目标是编程一个函数(ri(,该函数(ri(返回包含json文件中术语i的行数,因为我开始寻找我初始化的单词,但是随后,我不知道如何概括。这是我的开始代码:

public class rit {
private static final String filePath = "D:\c4\11\test.json"; 
    public static void main(String[] args) throws FileNotFoundException, ParseException, IOException {
        try{
             InputStream ips=new FileInputStream(filePath);
             InputStreamReader ipsr=new InputStreamReader(ips);
             BufferedReader br=new BufferedReader(ipsr);
             String ligne;
                 String mot="feel";
                 int i=1;
                // nombre de lignes  totales contenant le terme
                int nbre=0; 
             while ((ligne=br.readLine())!=null){
          try {
            // read the json file
                JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(ligne);
               // get a number from the JSON object
            String text =  (String) jsonObject.get("text");
                        if ( text.contains(mot)){
                        nbre++;
                        System.out.println("Mot trouvé a la ligne " + i );
                        i++;
                        }   
        } catch (ParseException ex) {
            ex.printStackTrace();
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        }}
               System.out.println("number of lines Which contain the term: " +nbre);
    br.close();
 }    
 catch (Exception e){
    System.out.println(e.toString());
 }}}

,输出为:

Mot trouvé a la ligne 1
Mot trouvé a la ligne 2
number of lines Which contain the term: 2

如果有可能概括,如何执行此操作?

public static void main(String[] args)中的String args[]是输入参数。因此,对于运行java rit.class feelargs将为[feel]

您可以在那些输入参数中使程序期待单词(甚至是filepath(:

public static void main(String[] args) {
    if(args.length != 2){
        // crash the application with an error message
        throw new IllegalArgumentException("Please enter $filePath and $wordToFind as input parameters");
    }
    String filePath = args[0];
    String mot = args[1];
    System.out.println("filePath : "+filePath);
    System.out.println("mot : "+mot);
}

另一种方法是等待用户输入。它很整洁,因为您可以将其包裹在循环中并重复使用:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in); // used for scanning user input
    while(true){
        System.out.println("please enter a word : ");
        String mot = scanner.nextLine();  // wait for user to input a word and enter
        System.out.println("mot is : "+mot);
    }
}

最新更新