1 /* 
2  * Copyright 2005 Paul Hinds
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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 */
16package org.tp23.antinstaller.selfextract;
17
18import java.io.BufferedReader;
19import java.io.File;
20import java.io.FileOutputStream;
21import java.io.IOException;
22import java.io.InputStream;
23import java.io.InputStreamReader;
24/**
25 * Copies resources from the Classpath to the filesystem replacing regex with replacement
26 * and correcting line endings
27 * @author teknopaul
28 *
29 */
30public class ResourceExtractor {
31    
32    /**
33     * @param resource Must start with / e.g. /org/tp23/myFile.txt
34     * @param dest
35     * @throws IOException 
36     */
37    public void copyResource(String resource, File dest, String regex, String replace) throws IOException{
38        InputStream is = this.getClass().getResourceAsStream(resource);
39        if(is == null){
40            throw new IOException("Can not find resource: " + resource);
41        }
42        InputStreamReader isr = new InputStreamReader(is);
43        BufferedReader br = new BufferedReader(isr);
44        FileOutputStream bos = new FileOutputStream(dest);
45        String line = null;
46        while((line = br.readLine()) != null){
47            bos.write(line.replaceAll(regex, replace).getBytes());
48            bos.write(System.getProperty("line.separator").getBytes());
49        }
50        bos.flush();
51        bos.close();
52        br.close();
53    }
54    /**
55     * @param resource Must start with / e.g. /org/tp23/myFile.txt
56     * @param dest
57     * @throws IOException 
58     */
59    public void copyResourceBinary(String resource, File dest) throws IOException{
60        InputStream is = this.getClass().getResourceAsStream(resource);
61        if(is == null){
62            throw new IOException("Can not find resource: " + resource);
63        }
64        FileOutputStream bos = new FileOutputStream(dest);
65        byte[] buffer = new byte[1024];
66        for(int read = 0; (read = is.read(buffer)) > 0; ){
67            bos.write(buffer, 0, read);
68        }
69        bos.flush();
70        bos.close();
71        is.close();
72    }
73
74}
75