2011-12-23 72 views
2

我有一个Ruby代码,它逐行读取文件,并检查是否需要读取某个块的下一行,或者它应该处理该块并继续读取文件解析每行。Java - 用readLine读取文件为

这是它:

File.open(ARGV[0], 'rb') do |f| 
    fl = false 
    text = '' 

    f.readlines.each do |line| 
     if (line =~ /^end_block/) 
      fl = false 

      # parse text variable 
     end 

     text += line if fl == true 

     if (line =~ /^start_block/) 
      fl = true 
     end 
    end 
end 

例如我需要打开文件作为二进制阅读,但我仍然需要一个readLine方法。

所以,问题是:我该怎么办一模一样使用Groovy/Java的?

+0

这个“二进制”怎么样? – fge 2011-12-23 10:32:05

+0

@fge抱歉,不明白你的问题... – shybovycha 2011-12-23 10:32:38

+0

@不好意思,什么? – shybovycha 2011-12-23 10:34:42

回答

2

您可以使用java.io.DataInputStream它同时提供一个readLine()方法和readFully(byte[])read(byte[])方法。

警告:JavaDoc for readLine表示,它被弃用,并且编码可能不合适(阅读JavaDoc中的详细信息)。

因此,请仔细考虑您的真实需求,如果这是您的案例中的适当折衷。

1

如果你有行格式的文本,这不是二进制的恕我直言。这是因为真正的二进制可以有任何字节,即使在代码中会产生假中断,即使是new linecarriage return也是如此。

你可能意味着你有文本在哪里你想读取每个字节没有编码或可能改变他们。这与使用ISO-8859-1相同。

您可以尝试

BufferedReader br = new BufferedReader(new InputStreamReader(
         new FileInputStream(filename), "ISO-8859-1")); 
StringBuilder sb = new StringBuilder(); 
String line; 
boolean include = false; 
while((line = br.readLine()) != null) { 
    if (line.startsWith("end_block")) 
     include = false; 
    else if (line.startsWith("start_block")) 
     include = true; 
    else if (include) 
     sb.append(line).append('\n'); // new lines back in. 
} 
br.close(); 
String text = sb.toString(); 
+0

好吧,我正试图在这些文本块上调用Inflate。所以,我需要他们是二元的。无所谓我如何做到这一点(像这里:http://stackoverflow.com/questions/8322615/read-file-content-line-by-line-from-byte-in-groovy)我得到'java.util .zip.DataFormatException:未知的压缩方法异常。所以,我认为这可能是由错误的文件阅读格式造成的...... – shybovycha 2011-12-23 10:39:34

+0

当您读取ZIP压缩文件时,首先必须对其进行解压缩。您可以先在Java中或在命令行上执行此操作。它不仅仅知道将压缩文件读取为未压缩的数据。 (如果Ruby自动为你做这件事,我会感到惊讶) – 2011-12-23 10:44:58

+0

鉴于你的错误信息,你确定它是用ZIP压缩的吗? – 2011-12-23 10:46:38

0

也许是这样的:

public final class Read 
{ 
    private static final Pattern START_BLOCK = Pattern.compile("whatever"); 
    private static final Pattern END_BLOCK = Pattern.compile("whatever"); 

    public static void main(final String... args) 
     throws IOException 
    { 
     if (args.length < 1) { 
      System.err.println("Not enough arguments"); 
      System.exit(1); 
     } 

     final FileReader r = new FileReader(args[0]); 
     final BufferedReader reader = new BufferedReader(r); 
     final StringBuilder sb = new StringBuilder(); 

     boolean inBlock = false; 

     String line; 

     while ((line = reader.readLine()) != null) { 
      if (END_BLOCK.matcher(line).matches()) { 
       inBlock = false; 
       continue; 
      } 

      if (inBlock) 
       sb.append(line); 

      if (START_BLOCK.matcher(line).matches()) 
       inBlock = true; 
     } 

     System.out.println(sb.toString()); 
     System.exit(0); 
    } 
}