1
18 package net.bull.javamelody.internal.common;
19
20 import java.io.ByteArrayOutputStream;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.nio.charset.Charset;
28 import java.util.zip.ZipEntry;
29 import java.util.zip.ZipOutputStream;
30
31
35 public final class InputOutput {
36 private InputOutput() {
37 super();
38 }
39
40 public static void pump(InputStream input, OutputStream output) throws IOException {
41 final byte[] bytes = new byte[4 * 1024];
42 int length = input.read(bytes);
43 while (length != -1) {
44 output.write(bytes, 0, length);
45 length = input.read(bytes);
46 }
47 }
48
49 public static byte[] pumpToByteArray(InputStream input) throws IOException {
50 final ByteArrayOutputStream out = new ByteArrayOutputStream();
51 pump(input, out);
52 return out.toByteArray();
53 }
54
55 public static String pumpToString(InputStream input, Charset charset) throws IOException {
56 final ByteArrayOutputStream out = new ByteArrayOutputStream();
57 pump(input, out);
58 return out.toString(charset.name());
59 }
60
61 public static void pumpToFile(InputStream input, File file) throws IOException {
62 try (OutputStream output = new FileOutputStream(file)) {
63 pump(input, output);
64 }
65 }
66
67 public static void pumpFromFile(File file, OutputStream output) throws IOException {
68 try (FileInputStream in = new FileInputStream(file)) {
69 pump(in, output);
70 }
71 }
72
73 public static void zipFile(File source, File target) throws IOException {
74 final FileOutputStream fos = new FileOutputStream(target);
75 try (ZipOutputStream zos = new ZipOutputStream(fos)) {
76 final ZipEntry ze = new ZipEntry(source.getName());
77 zos.putNextEntry(ze);
78 pumpFromFile(source, zos);
79 zos.closeEntry();
80 }
81 }
82
83 public static boolean deleteFile(File file) {
84 return file.delete();
85 }
86
87 public static void copyFile(File source, File target) throws IOException {
88 try (FileInputStream in = new FileInputStream(source);
89 FileOutputStream out = new FileOutputStream(target)) {
90 pump(in, out);
91 }
92 }
93 }
94