]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/StreamUtils.java
Improve ACR, introduce migration from JCR.
[lgpl/argeo-commons.git] / org.argeo.util / src / org / argeo / util / StreamUtils.java
1 package org.argeo.util;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.io.Reader;
8 import java.io.Writer;
9 import java.util.StringJoiner;
10
11 /** Stream utilities to be used when Apache Commons IO is not available. */
12 public class StreamUtils {
13 private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
14
15 /*
16 * APACHE COMMONS IO (inspired)
17 */
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 void closeQuietly(InputStream in) {
48 if (in != null)
49 try {
50 in.close();
51 } catch (Exception e) {
52 //
53 }
54 }
55
56 public static void closeQuietly(OutputStream out) {
57 if (out != null)
58 try {
59 out.close();
60 } catch (Exception e) {
61 //
62 }
63 }
64
65 public static void closeQuietly(Reader in) {
66 if (in != null)
67 try {
68 in.close();
69 } catch (Exception e) {
70 //
71 }
72 }
73
74 public static void closeQuietly(Writer out) {
75 if (out != null)
76 try {
77 out.close();
78 } catch (Exception e) {
79 //
80 }
81 }
82
83 public static String toString(BufferedReader reader) throws IOException {
84 StringJoiner sn = new StringJoiner("\n");
85 String line = null;
86 while ((line = reader.readLine()) != null)
87 sn.add(line);
88 return sn.toString();
89 }
90 }