01: package liquibase.util;
02:
03: import java.io.*;
04:
05: /**
06: * Utilities for working with streams.
07: */
08: public class StreamUtil {
09:
10: public static String getLineSeparator() {
11: return System.getProperty("line.separator");
12: }
13:
14: /**
15: * Reads a stream until the end of file into a String and uses the machines
16: * default encoding to convert to characters the bytes from the Stream.
17: *
18: * @param ins The InputStream to read.
19: * @return The contents of the input stream as a String
20: * @throws IOException If there is an error reading the stream.
21: */
22: public static String getStreamContents(InputStream ins)
23: throws IOException {
24:
25: InputStreamReader reader = new InputStreamReader(ins);
26: return getReaderContents(reader);
27: }
28:
29: /**
30: * Reads a stream until the end of file into a String and uses the machines
31: * default encoding to convert to characters the bytes from the Stream.
32: *
33: * @param ins The InputStream to read.
34: * @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
35: * @return The contents of the input stream as a String
36: * @throws IOException If there is an error reading the stream.
37: */
38: public static String getStreamContents(InputStream ins,
39: String charsetName) throws IOException {
40:
41: InputStreamReader reader = (charsetName != null) ? new InputStreamReader(
42: ins, charsetName)
43: : new InputStreamReader(ins);
44: return getReaderContents(reader);
45: }
46:
47: /**
48: * Reads all the characters into a String.
49: *
50: * @param reader The Reader to read.
51: * @return The contents of the input stream as a String
52: * @throws IOException If there is an error reading the stream.
53: */
54: public static String getReaderContents(Reader reader)
55: throws IOException {
56: try {
57: StringBuffer result = new StringBuffer();
58:
59: char[] buffer = new char[2048];
60: int read;
61: while ((read = reader.read(buffer)) > -1) {
62: result.append(buffer, 0, read);
63: }
64: return result.toString();
65: } finally {
66: try {
67: reader.close();
68: } catch (IOException ioe) {//NOPMD
69: // can safely ignore
70: }
71: }
72: }
73:
74: public static void copy(InputStream inputStream,
75: OutputStream outputStream) throws IOException {
76: byte[] bytes = new byte[1024];
77: int r = inputStream.read(bytes);
78: while (r > 0) {
79: outputStream.write(bytes, 0, r);
80: r = inputStream.read(bytes);
81: }
82: }
83: }
|