Blame view

src/main/java/com/jfinal/weixin/sdk/utils/IOUtils.java 2.25 KB
e80df919   atao   init
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  package com.jfinal.weixin.sdk.utils;
  
  import java.io.*;
  import java.nio.charset.Charset;
  
  /**
   * IOUtils
   * @author L.cm
   */
  public abstract class IOUtils {
      private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
  
      /**
       * closeQuietly
       * @param closeable 自动关闭
       */
      public static void closeQuietly(Closeable closeable) {
          try {
              if (closeable != null) {
                  closeable.close();
              }
          } catch (IOException ioe) {
              // ignore
          }
      }
  
      /**
       * InputStream to String utf-8
       *
       * @param input  the <code>InputStream</code> to read from
       * @return the requested String
       * @throws NullPointerException if the input is null
       * @throws IOException if an I/O error occurs
       */
      public static String toString(InputStream input) throws IOException {
          return toString(input, Charsets.UTF_8);
      }
  
      /**
       * InputStream to String
       *
       * @param input  the <code>InputStream</code> to read from
       * @param charset  the <code>Charset</code>
       * @return the requested String
       * @throws NullPointerException if the input is null
       * @throws IOException if an I/O error occurs
       */
      public static String toString(InputStream input, Charset charset) throws IOException {
          InputStreamReader in = new InputStreamReader(input, charset);
          StringBuffer out = new StringBuffer();
          char[] c = new char[DEFAULT_BUFFER_SIZE];
          for (int n; (n = in.read(c)) != -1;) {
              out.append(new String(c, 0, n));
          }
          IOUtils.closeQuietly(in);
          IOUtils.closeQuietly(input);
          return out.toString();
      }
  
      /**
       * InputStream to File
       * @param input  the <code>InputStream</code> to read from
       * @param file the File to write
       * @throws IOException id异常
       */
      public static void toFile(InputStream input, File file) throws IOException {
          OutputStream os = new FileOutputStream(file);
          int bytesRead = 0;
          byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
          while ((bytesRead = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
              os.write(buffer, 0, bytesRead);
          }
          IOUtils.closeQuietly(os);
          IOUtils.closeQuietly(input);
      }
  }