有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java读取并查找文件大小为1GB的行

我需要读取大于1GB的文本文件以查找特定行。这应该用Perl、PHP或Java编写。此方法不应加载服务器

有哪些方法可以做到这一点


共 (4) 个答案

  1. # 1 楼答案

    作为一行:

    perl -nwe 'print if /source-regex/' input.txt > output.txt
    

    作为脚本:

    use strict;
    use warnings;
    
    while (<>) {
        print if /source-regex/;
    }
    

    用法:perl script.pl input.txt > output.txt

    有很多方法可以优化这一点,但利用您提供的信息无法做更多的事情。搜索将需要一些时间,可能会很慢,具体取决于您的正则表达式

    如果您有安全问题,则显式打开文件更安全:

    open my $input, '<', shift or die $!;
    while (<$input>) { 
    ...
    
  2. # 2 楼答案

    在perl中:

    use strict;
    use warnings;
    
    my $line = 'what to be searched';
    open my $fh, '<', '/path/to/the/file' or die "unable to open file: $!";
    while(<$fh>) {
        chomp;
        if ($_ eq $line) {
            print "found $line at line $.\n";
            last;
        }
    }
    
  3. # 3 楼答案

    这里没有太多要说的,但是创建一个BufferedReader,一次读一行,看看它是否就是你要找的那一行

  4. # 4 楼答案

    如果你有一种“为正确的工作使用正确的工具”的态度,并且可以费心学习新的工具,perl、awk甚至sed都是非常适合这种工作的工具。否则,任何完整的语言都可以,Java也可以完成这项工作。但是使用缓冲类,比如BufferedReader,否则速度会非常慢

    perl中的示例:

    use strict;
    use warnings;
    
    open INFILE, "<infile" or die;
    open OUTFILE, ">outfile" or die;
    while(<INFILE>) {
      $_=~s/source-regex/replace-with/g;
      print OUTFILE;
    }
    

    我觉得一个班轮行得通,但有点复杂