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;
20 * APACHE COMMONS IO (inspired)
23 /** @return the number of bytes */
24 public static Long
copy(InputStream in
, OutputStream out
) throws IOException
{
26 byte[] buf
= new byte[DEFAULT_BUFFER_SIZE
];
28 int length
= in
.read(buf
);
31 out
.write(buf
, 0, length
);
32 count
= count
+ length
;
37 /** @return the number of chars */
38 public static Long
copy(Reader in
, Writer out
) throws IOException
{
40 char[] buf
= new char[DEFAULT_BUFFER_SIZE
];
42 int length
= in
.read(buf
);
45 out
.write(buf
, 0, length
);
46 count
= count
+ length
;
51 public static byte[] toByteArray(InputStream in
) throws IOException
{
52 try (ByteArrayOutputStream out
= new ByteArrayOutputStream()) {
54 return out
.toByteArray();
58 public static void closeQuietly(InputStream in
) {
62 } catch (Exception e
) {
67 public static void closeQuietly(OutputStream out
) {
71 } catch (Exception e
) {
76 public static void closeQuietly(Reader in
) {
80 } catch (Exception e
) {
85 public static void closeQuietly(Writer out
) {
89 } catch (Exception e
) {
94 public static String
toString(Class
<?
> clss
, String resource
) {
95 return toString(clss
.getResourceAsStream(resource
), StandardCharsets
.UTF_8
);
98 public static String
toString(InputStream in
) {
99 return toString(in
, StandardCharsets
.UTF_8
);
102 public static String
toString(InputStream in
, Charset encoding
) {
104 return new String(in
.readAllBytes(), encoding
);
105 } catch (IOException e
) {
106 throw new UncheckedIOException(e
);
110 public static String
toString(BufferedReader reader
) throws IOException
{
111 StringJoiner sn
= new StringJoiner("\n");
113 while ((line
= reader
.readLine()) != null)
115 return sn
.toString();