com.github.akurilov.commons.io.TextStreamOutput Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-commons Show documentation
Show all versions of java-commons Show documentation
Common functionality Java library
package com.github.akurilov.commons.io;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
/**
* The input implementation designed to write the text lines using {@link BufferedWriter}
*/
public abstract class TextStreamOutput
implements Output {
private static final ThreadLocal THRLOC_STRB = ThreadLocal.withInitial(
StringBuilder::new
);
private static final String LINE_SEP = System.getProperty("line.separator");
protected final BufferedWriter writer;
public TextStreamOutput(final OutputStream out)
throws IOException {
writer = new BufferedWriter(new OutputStreamWriter(out));
}
public TextStreamOutput(final OutputStream out, final int buffSize)
throws IOException {
writer = new BufferedWriter(new OutputStreamWriter(out), buffSize);
}
@Override
public boolean put(final String line)
throws IOException {
writer.write(line + LINE_SEP);
return true;
}
/**
* Uses the thread local string builder to concatenate the lines into the single text block for better performance
* @throws IOException
*/
@Override
public int put(final List lines, final int from, final int to)
throws IOException {
final StringBuilder strb = THRLOC_STRB.get();
strb.setLength(0);
for(int i = from; i < to; i ++) {
strb.append(lines.get(i));
strb.append(LINE_SEP);
}
writer.write(strb.toString());
return to - from;
}
/**
* Uses the thread local string builder to concatenate the lines into the single text block for better performance
* @throws IOException
*/
@Override
public int put(final List lines)
throws IOException {
final StringBuilder strb = THRLOC_STRB.get();
strb.setLength(0);
for(final String line : lines) {
strb.append(line);
strb.append(LINE_SEP);
}
writer.write(strb.toString());
return lines.size();
}
@Override
public void close()
throws IOException {
writer.flush();
writer.close();
}
}