1 package org
.argeo
.cms
.util
;
3 import java
.io
.BufferedReader
;
4 import java
.io
.ByteArrayOutputStream
;
5 import java
.io
.IOException
;
6 import java
.io
.InputStream
;
7 import java
.io
.OutputStream
;
9 import java
.io
.UncheckedIOException
;
10 import java
.io
.Writer
;
11 import java
.nio
.charset
.Charset
;
12 import java
.nio
.charset
.StandardCharsets
;
13 import java
.util
.StringJoiner
;
15 /** Stream utilities to be used when Apache Commons IO is not available. */
16 public class StreamUtils
{
17 private static final int DEFAULT_BUFFER_SIZE
= 1024 * 4;
19 /** @return the number of bytes */
20 public static long copy(InputStream in
, OutputStream out
) throws IOException
{
22 byte[] buf
= new byte[DEFAULT_BUFFER_SIZE
];
24 int length
= in
.read(buf
);
27 out
.write(buf
, 0, length
);
28 count
= count
+ length
;
33 /** @return the number of chars */
34 public static long copy(Reader in
, Writer out
) throws IOException
{
36 char[] buf
= new char[DEFAULT_BUFFER_SIZE
];
38 int length
= in
.read(buf
);
41 out
.write(buf
, 0, length
);
42 count
= count
+ length
;
47 public static byte[] toByteArray(InputStream in
) throws IOException
{
48 try (ByteArrayOutputStream out
= new ByteArrayOutputStream()) {
50 return out
.toByteArray();
54 public static void closeQuietly(InputStream in
) {
58 } catch (Exception e
) {
63 public static void closeQuietly(OutputStream out
) {
67 } catch (Exception e
) {
72 public static void closeQuietly(Reader in
) {
76 } catch (Exception e
) {
81 public static void closeQuietly(Writer out
) {
85 } catch (Exception e
) {
90 public static String
toString(Class
<?
> clss
, String resource
) {
91 return toString(clss
.getResourceAsStream(resource
), StandardCharsets
.UTF_8
);
94 public static String
toString(InputStream in
) {
95 return toString(in
, StandardCharsets
.UTF_8
);
98 public static String
toString(InputStream in
, Charset encoding
) {
100 return new String(in
.readAllBytes(), encoding
);
101 } catch (IOException e
) {
102 throw new UncheckedIOException(e
);
106 public static String
toString(BufferedReader reader
) throws IOException
{
107 StringJoiner sn
= new StringJoiner("\n");
109 while ((line
= reader
.readLine()) != null)
111 return sn
.toString();