【问题标题】:Reading Huge Data With Java [closed]使用 Java 读取海量数据 [关闭]
【发布时间】:2013-06-15 10:24:55
【问题描述】:

首先,对不起我的英语。

我正在寻找一种有效的方法来读取 java 中的大文件。我做了一个日志分析程序,我有至少 500 MB 到 4 GB 的日志文件。我已经尝试过 Filechannel 类(内存映射文件),但我无法获得有效的结果。看这里:http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_029.htm

我的目的是读取缓冲区中的数据,然后使用正则表达式。

DumpFilePath 文件大小约为 4 GB。

public static List<String> anaysis_main(String pattern_string) throws IOException {

    List<String> result = new ArrayList<String>();
    Pattern pattern = Pattern.compile(pattern_string, Pattern.CASE_INSENSITIVE);


    File file = new File(DumpFilePath);

    RandomAccessFile raf = new RandomAccessFile(file,"rw");
    String line = null;
    raf.seek(0);


    int i = 0;

    while((line=raf.readLine())!=null)
    {
        Matcher matcher = pattern.matcher(line);
        while (matcher.find())
        {               
            result.add(matcher.group(1));
        }
    }
    raf.close();

    return result;
}

有什么想法吗?

【问题讨论】:

  • FileChannel 要走的路;但是,映射的大小限制为 2 GB,因此您必须执行“滑动窗口”才能阅读。
  • 不知道为什么这被否决了......人们是否因为“与 的工作相比,4Gb 太小了!”而嗤之以鼻?还是因为英语有点生硬(她/他为此道歉)?长大。问题非常清楚:“如何将正则表达式应用于 4Gb 文件?”
  • 这里有一个建议:文件是否被划分为更小的单元(例如行),以使您要应用的正则表达式永远不会跨越多个单元?如果是这样,那么只需一次将一个单元读入内存,并将您的正则表达式应用于每个单元。
  • 既然你说你的数据是面向行的,那你为什么不使用一个普通的BufferedReader
  • 为什么没有效果(比如CPU使用的内存使用)?你有什么问题?

标签: java regex logging bigdata filechannel


【解决方案1】:

您可以使用缓冲阅读器吗?更多内容可以在buffered reader here阅读。

代码如下所示:

File file = new File(DumpFilePath);

//Open the file for reading
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((thisLine = br.readLine()) != null) { 

    // Your line by line parsing payload here

    Matcher matcher = pattern.matcher(thisLine);
    while (matcher.find())
    {               
        result.add(matcher.group(1));
        }

} // end while 
} // end try
catch (IOException e) {
System.err.println("Error: " + e);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多