Java – 使用readLine将文件读取为二进制文件

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

这是它:

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 完全相同

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

警告readLine的JavaDoc说,它已被弃用,编码可能不合适(在JavaDoc中读取详细信息)。

因此,请考虑您的实际要求,以及在您的情况下这是否适合权衡。

如果您有行格式化文本,那不是二进制恕我直言。 那是因为真正的二进制文件可以包含任何字节,甚至是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(); 

也许是这样的:

 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); } }