Java - 如何逐字而不是逐行读取大文件?

Rai*_*low 6 java

我想阅读Java中的"text8"语料库并重新格式化一些单词.问题是,在这个100MB的语料库中,所有单词都在一行上.因此,如果我尝试使用BufferedReader和加载它readLine,它会立即占用太多空间而无法处理它以分隔一个列表/数组中的所有单词.

所以我的问题是:在Java中是否有可能逐行读取语料库,逐字逐句阅读?那么例如因为所有单词都在一行上,例如每次迭代读取100个单词?

naf*_*fas 6

您可以尝试使用Scanner并将分隔符设置为适合您的任何内容:

Scanner input=new Scanner(myFile);
input.useDelimiter(" +"); //delimitor is one or more spaces

while(input.hasNext()){
  System.out.println(input.next());
}
Run Code Online (Sandbox Code Playgroud)


MiK*_*iKE 2

我建议您使用“字符流”FileReader

这是来自http://www.tutorialspoint.com/java/java_files_io.htm的示例代码

import java.io.*;

public class CopyFile {
   public static void main(String args[]) throws IOException
   {
      FileReader in = null;
      FileWriter out = null;

      try {
         in = new FileReader("input.txt");
         out = new FileWriter("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

它读取 16 位 Unicode 字符。这样,您的文本是否在一整行中都没关系。

由于您尝试逐字搜索,因此您可以轻松阅读,直到您偶然发现一个空格,然后您的单词就出现了。