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 package org.archive.crawler.util;
27
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.net.URL;
34
35 import org.apache.tools.ant.Project;
36 import org.apache.tools.ant.Target;
37 import org.apache.tools.ant.taskdefs.Expand;
38 import org.archive.net.UURI;
39
40 /***
41 * Logging utils.
42 * @author stack
43 */
44 public class IoUtils {
45 public static InputStream getInputStream(String pathOrUrl) {
46 return getInputStream(null, pathOrUrl);
47 }
48
49 /***
50 * Get inputstream.
51 *
52 * This method looks at passed string and tries to judge it a
53 * filesystem path or an URL. It then gets an InputStream on to
54 * the file or URL.
55 *
56 * <p>ASSUMPTION: Scheme on any url will probably only ever be 'file'
57 * or 'http'.
58 *
59 * @param basedir If passed <code>fileOrUrl</code> is a file path and
60 * it is not absolute, prefix with this basedir (May be null then
61 * no prefixing will be done).
62 * @param pathOrUrl Pass path to a file on disk or pass in a URL.
63 * @return An input stream.
64 */
65 public static InputStream getInputStream(File basedir, String pathOrUrl) {
66 InputStream is = null;
67 if (UURI.hasScheme(pathOrUrl)) {
68 try {
69 URL url = new URL(pathOrUrl);
70 is = url.openStream();
71 } catch (IOException e) {
72 e.printStackTrace();
73 }
74 } else {
75
76
77 File source = new File(pathOrUrl);
78 if (!source.isAbsolute() && basedir != null) {
79 source = new File(basedir, pathOrUrl);
80 }
81 try {
82 is = new FileInputStream(source);
83 } catch (FileNotFoundException e) {
84 e.printStackTrace();
85 }
86 }
87 return is;
88 }
89
90 /***
91 * Use ant to unjar.
92 * @param zipFile File to unzip.
93 * @param destinationDir Where to unzip to.
94 */
95 public static void unzip(File zipFile, File destinationDir) {
96 unzip(zipFile, destinationDir, true);
97 }
98
99 /***
100 * Use ant to unjar.
101 * @param zipFile File to unzip.
102 * @param destinationDir Where to unzip to.
103 * @param overwrite Whether to overwrite existing content.
104 */
105 public static void unzip(File zipFile, File destinationDir,
106 boolean overwrite) {
107 final class Expander extends Expand {
108 public Expander() {
109 }
110 }
111 Expander expander = new Expander();
112 expander.setProject(new Project());
113 expander.getProject().init();
114 expander.setTaskType("unzip");
115 expander.setTaskName("unzip");
116 expander.setOwningTarget(new Target());
117 expander.setSrc(zipFile);
118 expander.setDest(destinationDir);
119 expander.setOverwrite(overwrite);
120 expander.execute();
121 }
122 }