Quick Writer : Writer « File Input Output « Java






Quick Writer

        
//package com.thoughtworks.xstream.core.util;

import java.io.IOException;
import java.io.Writer;

public class QuickWriter {

    private final Writer writer;
    private char[] buffer;
    private int pointer;

    public QuickWriter(Writer writer) {
        this(writer, 1024);
    }

    public QuickWriter(Writer writer, int bufferSize) {
        this.writer = writer;
        buffer = new char[bufferSize];
    }

    public void write(String str) {
        int len = str.length();
        if (pointer + len >= buffer.length) {
            flush();
            if (len > buffer.length) {
                raw(str.toCharArray());
                return;
            }
        }
        str.getChars(0, len, buffer, pointer);
        pointer += len;
    }

    public void write(char c) {
        if (pointer + 1 >= buffer.length) {
            flush();
        }
        buffer[pointer++] = c;
    }

    public void write(char[] c) {
        int len = c.length;
        if (pointer + len >= buffer.length) {
            flush();
            if (len > buffer.length) {
                raw(c);
                return;
            }
        }
        System.arraycopy(c, 0, buffer, pointer, len);
        pointer += len;
    }

    public void flush() {
        try {
            writer.write(buffer, 0, pointer);
            pointer = 0;
            writer.flush();
        } catch (IOException e) {
          System.out.println(e);
        }
    }

    public void close() {
        try {
            writer.write(buffer, 0, pointer);
            pointer = 0;
            writer.close();
        } catch (IOException e) {
          System.out.println(e);
        }
    }

    private void raw(char[] c) {
        try {
            writer.write(c);
            writer.flush();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Null Writer
2.String Buffer Writer
3.Provides Closable semantics ordinarily missing in a java.io.CharArrayWriter
4.A writer for char strings
5.Write the entire contents of the supplied string to the given writer. This method always flushes and closes the writer when finished.
6.Writes all characters from a Reader to a file using the default character encoding.
7.Reads characters available from the Reader and returns these characters as a String object.
8.Wraps a stream, printing to standard out everything that is written to it.
9.Writer that places all output on an {@link Appendable} target.