01: /*
02: * Copyright 2005 Paul Hinds
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.tp23.antinstaller.selfextract;
17:
18: import java.io.BufferedReader;
19: import java.io.File;
20: import java.io.FileOutputStream;
21: import java.io.IOException;
22: import java.io.InputStream;
23: import java.io.InputStreamReader;
24:
25: /**
26: * Copies resources from the Classpath to the filesystem replacing regex with replacement
27: * and correcting line endings
28: * @author teknopaul
29: *
30: */
31: public class ResourceExtractor {
32:
33: /**
34: * @param resource Must start with / e.g. /org/tp23/myFile.txt
35: * @param dest
36: * @throws IOException
37: */
38: public void copyResource(String resource, File dest, String regex,
39: String replace) throws IOException {
40: InputStream is = this .getClass().getResourceAsStream(resource);
41: if (is == null) {
42: throw new IOException("Can not find resource: " + resource);
43: }
44: InputStreamReader isr = new InputStreamReader(is);
45: BufferedReader br = new BufferedReader(isr);
46: FileOutputStream bos = new FileOutputStream(dest);
47: String line = null;
48: while ((line = br.readLine()) != null) {
49: bos.write(line.replaceAll(regex, replace).getBytes());
50: bos.write(System.getProperty("line.separator").getBytes());
51: }
52: bos.flush();
53: bos.close();
54: br.close();
55: }
56:
57: /**
58: * @param resource Must start with / e.g. /org/tp23/myFile.txt
59: * @param dest
60: * @throws IOException
61: */
62: public void copyResourceBinary(String resource, File dest)
63: throws IOException {
64: InputStream is = this .getClass().getResourceAsStream(resource);
65: if (is == null) {
66: throw new IOException("Can not find resource: " + resource);
67: }
68: FileOutputStream bos = new FileOutputStream(dest);
69: byte[] buffer = new byte[1024];
70: for (int read = 0; (read = is.read(buffer)) > 0;) {
71: bos.write(buffer, 0, read);
72: }
73: bos.flush();
74: bos.close();
75: is.close();
76: }
77:
78: }
|