001 package com.mockrunner.util.common; 002 003 import java.io.File; 004 import java.io.FileNotFoundException; 005 import java.io.FileReader; 006 import java.net.URL; 007 import java.net.URLDecoder; 008 import java.util.List; 009 010 import com.mockrunner.base.NestedApplicationException; 011 012 public class FileUtil 013 { 014 /** 015 * Reads all lines from a text file and adds them to a <code>List</code>. 016 * @param file the input file 017 * @return the <code>List</code> with the file lines 018 */ 019 public static List getLinesFromFile(File file) 020 { 021 List resultList = null; 022 FileReader reader = null; 023 try 024 { 025 reader = new FileReader(file); 026 resultList = StreamUtil.getLinesFromReader(reader); 027 } 028 catch(FileNotFoundException exc) 029 { 030 throw new NestedApplicationException(exc); 031 032 } 033 finally 034 { 035 if(null != reader) 036 { 037 try 038 { 039 reader.close(); 040 } 041 catch(Exception exc) 042 { 043 throw new NestedApplicationException(exc); 044 } 045 } 046 } 047 return resultList; 048 } 049 050 /** 051 * Tries to open the file from its absolute or relative path. If the file 052 * doesn't exist, tries to load the file with <code>getResource</code>. 053 * Throws a <code>FileNotFoundException</code> if the file cannot be found. 054 * @param fileName the file name 055 * @return the file as reader 056 * @throws FileNotFoundException if the cannot be found 057 */ 058 public static File findFile(String fileName) throws FileNotFoundException 059 { 060 File file = new File(fileName); 061 if(isExistingFile(file)) return file; 062 fileName = fileName.replace('\\', '/'); 063 file = new File(fileName); 064 if(isExistingFile(file)) return file; 065 URL fileURL = FileUtil.class.getClassLoader().getResource(fileName); 066 file = decodeFileURL(fileURL); 067 if(null != file) return file; 068 fileURL = FileUtil.class.getResource(fileName); 069 file = decodeFileURL(fileURL); 070 if(null != file) return file; 071 throw new FileNotFoundException("Could not find file: " + fileName); 072 } 073 074 private static File decodeFileURL(URL fileURL) 075 { 076 if(fileURL != null) 077 { 078 File file = new File(fileURL.getFile()); 079 if(isExistingFile(file)) return file; 080 file = new File(URLDecoder.decode(fileURL.getFile())); 081 if(isExistingFile(file)) return file; 082 } 083 return null; 084 } 085 086 private static boolean isExistingFile(File file) 087 { 088 return (file.exists() && file.isFile()); 089 } 090 }