All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.cattleframework.utils.auxiliary.StreamUtils Maven / Gradle / Ivy

There is a newer version: 1.0.1-M3
Show newest version
/*
 * Copyright (C) 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cattleframework.utils.auxiliary;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.cattleframework.exception.ExceptionWrapUtils;

/**
 * 流工具
 * 
 * @author orange
 *
 */
public final class StreamUtils {

    private static final int READ_BUFFER_LENGTH = 1024;

    private StreamUtils() {
    }

    public static String inputStream2String(InputStream is) {
	return inputStream2String(is, "UTF-8");
    }

    public static String inputStream2String(InputStream is, String charset) {
	byte[] bytes = inputStream2Bytes(is);
	try {
	    return new String(bytes, charset);
	} catch (UnsupportedEncodingException e) {
	    throw ExceptionWrapUtils.wrap(e);
	}
    }

    public static byte[] inputStream2Bytes(InputStream is) {
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
	    byte[] buffer = new byte[READ_BUFFER_LENGTH];
	    int c;
	    while ((c = is.read(buffer, 0, READ_BUFFER_LENGTH)) > 0) {
		baos.write(buffer, 0, c);
	    }
	    return baos.toByteArray();
	} catch (IOException e) {
	    throw ExceptionWrapUtils.wrap(e);
	}
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy