]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/util/StreamUtils.java
Prepare next development cycle
[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.Writer;
10 import java.util.StringJoiner;
11
12 /** Stream utilities to be used when Apache Commons IO is not available. */
13 public class StreamUtils {
14 private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
15
16 /*
17 * APACHE COMMONS IO (inspired)
18 */
19
20 /** @return the number of bytes */
21 public static Long copy(InputStream in, OutputStream out) throws IOException {
22 Long count = 0l;
23 byte[] buf = new byte[DEFAULT_BUFFER_SIZE];
24 while (true) {
25 int length = in.read(buf);
26 if (length < 0)
27 break;
28 out.write(buf, 0, length);
29 count = count + length;
30 }
31 return count;
32 }
33
34 /** @return the number of chars */
35 public static Long copy(Reader in, Writer out) throws IOException {
36 Long count = 0l;
37 char[] buf = new char[DEFAULT_BUFFER_SIZE];
38 while (true) {
39 int length = in.read(buf);
40 if (length < 0)
41 break;
42 out.write(buf, 0, length);
43 count = count + length;
44 }
45 return count;
46 }
47
48 public static byte[] toByteArray(InputStream in) throws IOException {
49 try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
50 copy(in, out);
51 return out.toByteArray();
52 }
53 }
54
55 public static void closeQuietly(InputStream in) {
56 if (in != null)
57 try {
58 in.close();
59 } catch (Exception e) {
60 //
61 }
62 }
63
64 public static void closeQuietly(OutputStream out) {
65 if (out != null)
66 try {
67 out.close();
68 } catch (Exception e) {
69 //
70 }
71 }
72
73 public static void closeQuietly(Reader in) {
74 if (in != null)
75 try {
76 in.close();
77 } catch (Exception e) {
78 //
79 }
80 }
81
82 public static void closeQuietly(Writer out) {
83 if (out != null)
84 try {
85 out.close();
86 } catch (Exception e) {
87 //
88 }
89 }
90
91 public static String toString(BufferedReader reader) throws IOException {
92 StringJoiner sn = new StringJoiner("\n");
93 String line = null;
94 while ((line = reader.readLine()) != null)
95 sn.add(line);
96 return sn.toString();
97 }
98 }