从日志文件中读取一TB数据

时间:2012-06-06 17:49:26

标签: java algorithm data-structures

如何读取两个大小为1 TB的日志文件,而不会耗尽我机器上的内存。我会对它们进行一些比较。我想在Java中这样做。下面的代码如下我担心的是FileStream无法保存日志文件的数据。

public static void main(String args[])
{
  try{
     // Open the file that is the first 
     // command line parameter
     FileInputStream fstream = new FileInputStream("textfile.txt");
     // Get the object of DataInputStream
     DataInputStream in = new DataInputStream(fstream);
     BufferedReader br = new BufferedReader(new InputStreamReader(in));
     String strLine;
     //Read File Line By Line
     while ((strLine = br.readLine()) != null) {
        // Print the content on the console
        System.out.println (strLine);
     }
     //Close the input stream
     in.close();
  }
  catch (Exception e){//Catch exception if any
     System.err.println("Error: " + e.getMessage());
  }
}

任何人都可以指导我这样做的正确方法。

1 个答案:

答案 0 :(得分:3)

您的代码可能会起作用,因为您只是将每一行加载到内存中。但是,一旦读取超过几百行,你就会丢失stdout缓冲区中的输出。

做比较的最好方法是将一些项目加载到一个集合中,然后丢弃那些你完成后不需要的项目。这将使内存使用率降低。如果你想要聪明一点,请密切关注你的进程的内存使用情况,并在达到固定的阈值时开始清理。

相关问题