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 package org.apache.http.impl.client.cache;
28
29 import java.io.Closeable;
30 import java.io.File;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.io.RandomAccessFile;
35 import java.nio.channels.FileChannel;
36
37 import org.apache.http.HttpEntity;
38
39 class IOUtils {
40
41 static void consume(final HttpEntity entity) throws IOException {
42 if (entity == null) {
43 return;
44 }
45 if (entity.isStreaming()) {
46 final InputStream inStream = entity.getContent();
47 if (inStream != null) {
48 inStream.close();
49 }
50 }
51 }
52
53 static void copy(final InputStream in, final OutputStream out) throws IOException {
54 final byte[] buf = new byte[2048];
55 int len;
56 while ((len = in.read(buf)) != -1) {
57 out.write(buf, 0, len);
58 }
59 }
60
61 static void closeSilently(final Closeable closable) {
62 try {
63 closable.close();
64 } catch (final IOException ignore) {
65 }
66 }
67
68 static void copyAndClose(final InputStream in, final OutputStream out) throws IOException {
69 try {
70 copy(in, out);
71 in.close();
72 out.close();
73 } catch (final IOException ex) {
74 closeSilently(in);
75 closeSilently(out);
76
77 throw ex;
78 }
79 }
80
81 static void copyFile(final File in, final File out) throws IOException {
82 final RandomAccessFile f1 = new RandomAccessFile(in, "r");
83 final RandomAccessFile f2 = new RandomAccessFile(out, "rw");
84 try {
85 final FileChannel c1 = f1.getChannel();
86 final FileChannel c2 = f2.getChannel();
87 try {
88 c1.transferTo(0, f1.length(), c2);
89 c1.close();
90 c2.close();
91 } catch (final IOException ex) {
92 closeSilently(c1);
93 closeSilently(c2);
94
95 throw ex;
96 }
97 f1.close();
98 f2.close();
99 } catch (final IOException ex) {
100 closeSilently(f1);
101 closeSilently(f2);
102
103 throw ex;
104 }
105 }
106
107 }