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

时间:2011-12-23 10:30:12

标签: java ruby file groovy

我有一个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

E.g。我需要打开文件作为二进制文件阅读,我仍然需要一个readLine方法。

所以,问题是:如何使用Groovy / Java 完全相同的

3 个答案:

答案 0 :(得分:2)

您可以使用提供java.io.DataInputStream方法以及readLine()readFully(byte[])方法的read(byte[])

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

请仔细考虑您的实际要求,以及这是否适用于您的情况。

答案 1 :(得分: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();

答案 2 :(得分: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);
    }
}