Java Text File Read by Charset copy(Reader input, OutputStream output, Charset encoding)

Here you can find the source of copy(Reader input, OutputStream output, Charset encoding)

Description

copy

License

Apache License

Declaration

public static void copy(Reader input, OutputStream output, Charset encoding) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;

public class Main {
    private static final int EOF = -1;
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    public static void copy(Reader input, OutputStream output, Charset encoding) throws IOException {
        OutputStreamWriter out = new OutputStreamWriter(output, encoding);
        copyLarge(input, out, new char[DEFAULT_BUFFER_SIZE]);
        out.flush();// ww  w  .j a  v  a 2s . c  o m
    }

    public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        if (count > Integer.MAX_VALUE) {
            return -1;
        }
        return (int) count;
    }

    private static long copyLarge(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    private static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
        long count = 0;
        int n = 0;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    private static long copyLarge(Reader input, Writer output, char[] buffer) throws IOException {
        long count = 0;
        int n = 0;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }
}

Related

  1. asReader(InputStream input, Charset charset)
  2. convert(File file, Charset from, String toEncoding, ByteArrayOutputStream bytearray, boolean headersOn, int totalLinesToRead)
  3. createBOMStrippedReader(InputStream stream, String defaultCharset)
  4. createBufferedReaderWithGuessedCharset(File file)
  5. createInputStreamReader(File file, String charsetName)
  6. createReader(Path p, Charset cs)