Java – Char读取文本文件Char的最快方法

我有近500个文本文件,1000万字。 我必须索引这些词。 从字符逐个字符读取文本文件的最快方法是什么? 这是我最初的尝试:

InputStream ist = new FileInputStream(this.path+"/"+doc); BufferedReader in = new BufferedReader(new InputStreamReader(ist)); String line; while((line = in.readLine()) != null){ line = line.toUpperCase(Locale.ENGLISH); String word = ""; for (int j = 0; j <= line.length(); j++) { char c= line.charAt(j); // OPERATIONS } 

read()不会给性能带来很大的差异。

阅读更多: Peter Lawery对read()和readLine()的比较

现在,回到原来的问题:
输入字符串: hello how are you?
所以你需要索引该行的单词 ,即:

 BufferedReader r = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = r.readLine()) != null) { String[] splitString = line.split("\\s+"); //Do stuff with the array here, ie construct the index. } 

注意:模式\\s+会在字符串中添加分隔符,如tab,space等任何空格。

InputStreamReader的read()方法一次可以读取一个字符。

您可以将其包装在FileReader或BufferedReader或示例中。

希望这可以帮助!

不要读取行,然后通过char重新扫描char行。 这样你就可以处理每个角色两次。 只需通过BufferedReader.read()读取字符。