阅读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中是否有任何方法可以获取下一个单词,还是必须拆分行字符串来获取单词?
您不一定要拆分该行,因为java.util.Scanner的默认分隔符是空格。
您可以在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); } }
您已经在代码的这一行中获得了下一行:
String line = sc.nextLine();
为了获得一行的话,我建议使用:
String[] words = line.split(" ");
使用Scanner
,您最终会为每一行产生大量对象。 您将为具有大文件的GC生成大量垃圾。 而且,它比使用split()慢近三倍。
另一方面,如果按空格分割( line.split(" ")
),如果尝试读取具有不同空白分隔符的文件,代码将失败。 如果split()
希望你编写一个正则表达式,并且它确实匹配,那么使用split("\\s")
代替匹配“bit”空格而不仅仅是空格字符。
PS:对不起,我没有权利对已经给出的答案发表评论。
你最好先阅读一条线然后进行拆分。
File file = new File("path/to/file"); String words[]; // I miss C String line; HashMap 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(); }
你可以使用Scanner逐字阅读,Scanner.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!"); }