001/* 002 * nimbus-jose-jwt 003 * 004 * Copyright 2012-2016, Connect2id Ltd and contributors. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.jose.util; 019 020 021import java.io.*; 022import java.nio.charset.Charset; 023 024 025/** 026 * Input / output utilities. 027 * 028 * @author Vladimir Dzhuvinov 029 * @version 2016-11-28 030 */ 031public class IOUtils { 032 033 034 /** 035 * Reads the specified input stream into a string. 036 * 037 * @param stream The input stream. Must not be {@code null}. 038 * @param charset The expected character set. Must not be {@code null}. 039 * 040 * @return The string. 041 * 042 * @throws IOException If an input exception is encountered. 043 */ 044 public static String readInputStreamToString(final InputStream stream, final Charset charset) 045 throws IOException { 046 047 final int bufferSize = 1024; 048 final char[] buffer = new char[bufferSize]; 049 final StringBuilder out = new StringBuilder(); 050 Reader in = new InputStreamReader(stream, charset); 051 052 while (true) { 053 int rsz = in.read(buffer, 0, buffer.length); 054 if (rsz < 0) 055 break; 056 out.append(buffer, 0, rsz); 057 } 058 059 return out.toString(); 060 } 061 062 063 /** 064 * Reads the content of the specified file into a string. 065 * 066 * @param file The file. Must not be {@code null}. 067 * @param charset The expected character set. Must not be {@code null}. 068 * 069 * @return The string. 070 * 071 * @throws IOException If an input exception is encountered. 072 */ 073 public static String readFileToString(final File file, final Charset charset) 074 throws IOException { 075 076 return readInputStreamToString(new FileInputStream(file), charset); 077 } 078 079 080 /** 081 * Prevents public instantiation. 082 */ 083 private IOUtils() {} 084}