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.util.List; 008 009 import com.mockrunner.base.NestedApplicationException; 010 011 public class FileUtil 012 { 013 /** 014 * Reads all lines from a text file and adds them to a <code>List</code>. 015 * @param file the input file 016 * @return the <code>List</code> with the file lines 017 */ 018 public static List getLinesFromFile(File file) 019 { 020 List resultList = null; 021 FileReader reader = null; 022 try 023 { 024 reader = new FileReader(file); 025 resultList = StreamUtil.getLinesFromReader(reader); 026 } 027 catch(FileNotFoundException exc) 028 { 029 throw new NestedApplicationException(exc); 030 031 } 032 finally 033 { 034 if(null != reader) 035 { 036 try 037 { 038 reader.close(); 039 } 040 catch(Exception exc) 041 { 042 throw new NestedApplicationException(exc); 043 } 044 } 045 } 046 return resultList; 047 } 048 049 /** 050 * Tries to open the file from its absolute or relative path. If the file 051 * doesn't exist, tries to load the file with <code>getResource</code>. 052 * Returns <code>null</code> if the file cannot be found. 053 * @param fileName the file name 054 * @return the file as reader 055 */ 056 public static File findFile(String fileName) 057 { 058 File file = new File(fileName); 059 try 060 { 061 if(file.exists() && file.isFile()) 062 { 063 return file; 064 } 065 URL fileURL = FileUtil.class.getClassLoader().getResource(fileName); 066 if (fileURL != null) return new File(fileURL.getFile()); 067 fileURL = FileUtil.class.getResource(fileName); 068 if (fileURL != null) return new File(fileURL.getFile()); 069 return null; 070 } 071 catch(Exception exc) 072 { 073 throw new NestedApplicationException("Error while trying to find the file " + fileName, exc); 074 } 075 } 076 }