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 2019-11-07 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 051 Reader in = new InputStreamReader(stream, charset); 052 try { 053 while (true) { 054 int rsz = in.read(buffer, 0, buffer.length); 055 if (rsz < 0) 056 break; 057 out.append(buffer, 0, rsz); 058 } 059 return out.toString(); 060 } finally { 061 in.close(); 062 } 063 } 064 065 066 /** 067 * Reads the content of the specified file into a string. 068 * 069 * @param file The file. Must not be {@code null}. 070 * @param charset The expected character set. Must not be {@code null}. 071 * 072 * @return The string. 073 * 074 * @throws IOException If an input exception is encountered. 075 */ 076 public static String readFileToString(final File file, final Charset charset) 077 throws IOException { 078 079 return readInputStreamToString(new FileInputStream(file), charset); 080 } 081 082 083 /** 084 * Prevents public instantiation. 085 */ 086 private IOUtils() {} 087}