1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.maven.common;
17
18 import java.io.File;
19 import java.io.FileInputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.apache.commons.io.FileUtils;
27 import org.apache.commons.io.IOUtils;
28 import org.springframework.core.io.DefaultResourceLoader;
29 import org.springframework.core.io.Resource;
30 import org.springframework.core.io.ResourceLoader;
31
32 public class ResourceUtils {
33 ResourceLoader loader = new DefaultResourceLoader();
34
35
36
37
38
39
40 public InputStream getInputStream(String location) throws IOException {
41 if (!exists(location)) {
42 throw new IOException("Unable to locate " + location);
43 }
44 File file = new File(location);
45 if (file.exists()) {
46 return new FileInputStream(file);
47 } else {
48 Resource resource = loader.getResource(location);
49 return resource.getInputStream();
50 }
51 }
52
53 public boolean exists(String location) {
54 File file = new File(location);
55 if (file.exists()) {
56 return true;
57 }
58 Resource resource = loader.getResource(location);
59 return resource.exists();
60 }
61
62
63
64
65 public void copy(String location, File file) throws IOException {
66 InputStream in = null;
67 OutputStream out = null;
68 try {
69 in = getInputStream(location);
70 out = FileUtils.openOutputStream(file);
71 IOUtils.copy(in, out);
72 } finally {
73 IOUtils.closeQuietly(in);
74 IOUtils.closeQuietly(out);
75 }
76 }
77
78
79
80
81 public void write(File file, String contents) throws IOException {
82 OutputStream out = null;
83 try {
84 out = FileUtils.openOutputStream(file);
85 IOUtils.write(contents, out);
86 } finally {
87 IOUtils.closeQuietly(out);
88 }
89
90 }
91
92 public List<String> read(List<String> locations) throws IOException {
93 List<String> contents = new ArrayList<String>();
94 for (String location : locations) {
95 String content = read(location);
96 contents.add(content);
97 }
98 return contents;
99 }
100
101
102
103
104 public String read(String location) throws IOException {
105 InputStream in = null;
106 try {
107 in = getInputStream(location);
108 return IOUtils.toString(in);
109 } finally {
110 IOUtils.closeQuietly(in);
111 }
112 }
113
114
115
116
117 public String getFilename(String location) throws IOException {
118 if (!exists(location)) {
119 throw new IOException("Unable to locate " + location);
120 }
121 File file = new File(location);
122 if (file.exists()) {
123 return file.getName();
124 } else {
125 Resource resource = loader.getResource(location);
126 return resource.getFilename();
127 }
128 }
129 }