01: package com.mockrunner.util.common;
02:
03: import java.io.File;
04: import java.io.FileNotFoundException;
05: import java.io.FileReader;
06: import java.net.URL;
07: import java.net.URLDecoder;
08: import java.util.List;
09:
10: import com.mockrunner.base.NestedApplicationException;
11:
12: public class FileUtil {
13: /**
14: * Reads all lines from a text file and adds them to a <code>List</code>.
15: * @param file the input file
16: * @return the <code>List</code> with the file lines
17: */
18: public static List getLinesFromFile(File file) {
19: List resultList = null;
20: FileReader reader = null;
21: try {
22: reader = new FileReader(file);
23: resultList = StreamUtil.getLinesFromReader(reader);
24: } catch (FileNotFoundException exc) {
25: throw new NestedApplicationException(exc);
26:
27: } finally {
28: if (null != reader) {
29: try {
30: reader.close();
31: } catch (Exception exc) {
32: throw new NestedApplicationException(exc);
33: }
34: }
35: }
36: return resultList;
37: }
38:
39: /**
40: * Tries to open the file from its absolute or relative path. If the file
41: * doesn't exist, tries to load the file with <code>getResource</code>.
42: * Throws a <code>FileNotFoundException</code> if the file cannot be found.
43: * @param fileName the file name
44: * @return the file as reader
45: * @throws FileNotFoundException if the cannot be found
46: */
47: public static File findFile(String fileName)
48: throws FileNotFoundException {
49: File file = new File(fileName);
50: if (isExistingFile(file))
51: return file;
52: fileName = fileName.replace('\\', '/');
53: file = new File(fileName);
54: if (isExistingFile(file))
55: return file;
56: URL fileURL = FileUtil.class.getClassLoader().getResource(
57: fileName);
58: file = decodeFileURL(fileURL);
59: if (null != file)
60: return file;
61: fileURL = FileUtil.class.getResource(fileName);
62: file = decodeFileURL(fileURL);
63: if (null != file)
64: return file;
65: throw new FileNotFoundException("Could not find file: "
66: + fileName);
67: }
68:
69: private static File decodeFileURL(URL fileURL) {
70: if (fileURL != null) {
71: File file = new File(fileURL.getFile());
72: if (isExistingFile(file))
73: return file;
74: file = new File(URLDecoder.decode(fileURL.getFile()));
75: if (isExistingFile(file))
76: return file;
77: }
78: return null;
79: }
80:
81: private static boolean isExistingFile(File file) {
82: return (file.exists() && file.isFile());
83: }
84: }
|