1 package com.foxinmy.weixin4j.util;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.Closeable;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.io.OutputStreamWriter;
9 import java.io.Reader;
10 import java.io.Writer;
11 import java.nio.charset.Charset;
12
13
14
15
16
17
18
19
20
21
22 public class IOUtil {
23
24 private static final int EOF = -1;
25 private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
26
27 public static byte[] toByteArray(Reader input) throws IOException {
28 return toByteArray(input, Charset.defaultCharset());
29 }
30
31 public static byte[] toByteArray(Reader input, Charset encoding) throws IOException {
32 ByteArrayOutputStream output = new ByteArrayOutputStream();
33 copy(input, output, encoding);
34 return output.toByteArray();
35 }
36
37 public static void copy(Reader input, OutputStream output, Charset encoding) throws IOException {
38 OutputStreamWriter out = new OutputStreamWriter(output, encoding);
39 copyLarge(input, out, new char[DEFAULT_BUFFER_SIZE]);
40 out.flush();
41 }
42
43 public static int copy(InputStream input, OutputStream output) throws IOException {
44 long count = copyLarge(input, output);
45 if (count > Integer.MAX_VALUE) {
46 return -1;
47 }
48 return (int) count;
49 }
50
51 private static long copyLarge(InputStream input, OutputStream output) throws IOException {
52 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
53 long count = 0;
54 int n = 0;
55 while (-1 != (n = input.read(buffer))) {
56 output.write(buffer, 0, n);
57 count += n;
58 }
59 return count;
60 }
61
62 public static byte[] toByteArray(InputStream input) throws IOException {
63 ByteArrayOutputStream output = new ByteArrayOutputStream();
64 copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]);
65 return output.toByteArray();
66 }
67
68 private static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
69 long count = 0;
70 int n = 0;
71 while (EOF != (n = input.read(buffer))) {
72 output.write(buffer, 0, n);
73 count += n;
74 }
75 return count;
76 }
77
78 private static long copyLarge(Reader input, Writer output, char[] buffer) throws IOException {
79 long count = 0;
80 int n = 0;
81 while (EOF != (n = input.read(buffer))) {
82 output.write(buffer, 0, n);
83 count += n;
84 }
85 return count;
86 }
87
88 public static void close(Closeable stream) {
89 try {
90 if(stream == null){
91 return ;
92 }
93 stream.close();
94 } catch (IOException e) {
95 e.printStackTrace();
96 }
97 }
98 }