有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。扫描仪读取java中的下一个单词

我有一个包含以下内容的文本文件:

ac und
accipio annehmen
ad zu
adeo hinzugehen
...

我阅读文本文件,并反复阅读以下行:

Scanner sc = new Scanner(new File("translate.txt"));
while(sc.hasNext()){
 String line = sc.nextLine();       
}

每行有两个单词。java中是否有任何方法来获取下一个单词,或者我是否必须拆分行字符串来获取单词


共 (5) 个答案

  1. # 1 楼答案

    你可以用扫描器逐字读,扫描器。next()读下一个单词

    try {
      Scanner s = new Scanner(new File(filename));
    
      while (s.hasNext()) {
        System.out.println("word:" + s.next());
      }
    } catch (IOException e) {
      System.out.println("Error accessing input file!");
    }
    
  2. # 2 楼答案

    因为java,所以不必拆分行。util。扫描仪的默认分隔符是空白

    您可以在while语句中创建一个新的Scanner对象

        Scanner sc2 = null;
        try {
            sc2 = new Scanner(new File("translate.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();  
        }
        while (sc2.hasNextLine()) {
                Scanner s2 = new Scanner(sc2.nextLine());
            while (s2.hasNext()) {
                String s = s2.next();
                System.out.println(s);
            }
        }
    
  3. # 3 楼答案

    你最好先读一行,然后再拆分

    File file = new File("path/to/file");
    String words[]; // I miss C
    String line;
    HashMap<String, String> hm = new HashMap<>();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")))
    {
        while((line = br.readLine() != null)){
            words = line.split("\\s");
            if (hm.containsKey(words[0])){
                    System.out.println("Found duplicate ... handle logic");
            }
            hm.put(words[0],words[1]); //if index==0 is ur key
        }
    
    } catch (FileNotFoundException e) {
            e.printStackTrace();
    } catch (IOException e) {
            e.printStackTrace();
    }
    
  4. # 4 楼答案

    使用Scanner可以为每一行生成大量对象。您将为带有大文件的GC生成相当多的垃圾。此外,它的速度几乎是使用split()的三倍

    另一方面,如果按空格分割(line.split(" ")),如果试图读取具有不同空格分隔符的文件,代码将失败。如果split()希望您编写一个正则表达式,并且它无论如何都会进行匹配,请使用split("\\s"),它匹配的空格比只匹配一个空格字符多一点

    注:对不起,我无权对已经给出的答案发表评论

  5. # 5 楼答案

    您已经得到了这一行代码中的下一行:

     String line = sc.nextLine();  
    

    要获得一行字,我建议使用:

    String[] words = line.split(" ");