]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/util/StreamUtils.java
Improve nested OSGi runtimes
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / util / StreamUtils.java
1 package org.argeo.cms.util;
2
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;
8 import java.io.Reader;
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;
14
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;
18
19 /** @return the number of bytes */
20 public static long copy(InputStream in, OutputStream out) throws IOException {
21 long count = 0l;
22 byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
23 while (true) {
24 int length = in.read(buf);
25 if (length < 0)
26 break;
27 out.write(buf, 0, length);
28 count = count + length;
29 }
30 return count;
31 }
32
33 /** @return the number of chars */
34 public static long copy(Reader in, Writer out) throws IOException {
35 long count = 0l;
36 char[] buf = new char[DEFAULT_BUFFER_SIZE];
37 while (true) {
38 int length = in.read(buf);
39 if (length < 0)
40 break;
41 out.write(buf, 0, length);
42 count = count + length;
43 }
44 return count;
45 }
46
47 public static byte[] toByteArray(InputStream in) throws IOException {
48 try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
49 copy(in, out);
50 return out.toByteArray();
51 }
52 }
53
54 public static void closeQuietly(InputStream in) {
55 if (in != null)
56 try {
57 in.close();
58 } catch (Exception e) {
59 //
60 }
61 }
62
63 public static void closeQuietly(OutputStream out) {
64 if (out != null)
65 try {
66 out.close();
67 } catch (Exception e) {
68 //
69 }
70 }
71
72 public static void closeQuietly(Reader in) {
73 if (in != null)
74 try {
75 in.close();
76 } catch (Exception e) {
77 //
78 }
79 }
80
81 public static void closeQuietly(Writer out) {
82 if (out != null)
83 try {
84 out.close();
85 } catch (Exception e) {
86 //
87 }
88 }
89
90 public static String toString(Class<?> clss, String resource) {
91 return toString(clss.getResourceAsStream(resource), StandardCharsets.UTF_8);
92 }
93
94 public static String toString(InputStream in) {
95 return toString(in, StandardCharsets.UTF_8);
96 }
97
98 public static String toString(InputStream in, Charset encoding) {
99 try {
100 return new String(in.readAllBytes(), encoding);
101 } catch (IOException e) {
102 throw new UncheckedIOException(e);
103 }
104 }
105
106 public static String toString(BufferedReader reader) throws IOException {
107 StringJoiner sn = new StringJoiner("\n");
108 String line = null;
109 while ((line = reader.readLine()) != null)
110 sn.add(line);
111 return sn.toString();
112 }
113 }