Home » Java » java – How to output all lines to a given writer and return the number of bytes-Exceptionshub

java – How to output all lines to a given writer and return the number of bytes-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

How can I output to a given writer all the rows in the list that consist only of Latin letters or numbers and return the number of successfully written bytes before the first exception using a lambda expression?

My code:

public int writeAllCountingBytesTransferred(Writer writer, List<String> list) {     
    return list.stream().filter(x -> x.matches("^[a-zA-Z0-9]+$") ).forEach(x-> {
        try {
            writer.write(x);
            how do I count bytes?
        } catch (IOException e) {
            how do I return bytes?

        }
    });        
}
How to&Answers:

I would map to an IntStream of the string lengths and sum() it:

return list.stream()
    .filter(x -> x.matches("^[a-zA-Z0-9]+$"))
    .mapToInt(x-> {
      try {
        writer.write(x);
        return x.length();
      } catch (IOException e) {
        return 0;
      }
    })
    .sum();

Note that when the strings are all letters and digits the char length and byte length are the same.

Answer:

public class CountingWriter extends FilterWriter {
    private long count;

    public CountingWriter(Writer out) {
        super(out);
    }

    /**
     * The number of chars written. For ASCII this is the number of bytes.
     * @return the char count.
     */
    public long getCount() {
        return count;
    }

    @Override
    public void write(int c) throws IOException {
        super.write(c);
        ++count;
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        super.write(cbuf, off, len);
        count += len;
    }

    @Override
    public void write(String str, int off, int len) throws IOException {
        super.write(str, off, len);
        count += len;
    }
}

CountingWriter cWriter = new CountingWriter(writer);
...
long count = cWriter.getCount();

A FilterWriter is a nice wrapper class that delegates to the original writer, and can be used for this kind of filtering purposes.

As ASCII implies that every char is written as a single byte. (If the encoding for the file is not UTF-16LE or such.)