001 /** 002 * FileIO.java 003 * jCOLIBRI2 framework. 004 * @author Juan A. Recio-García. 005 * GAIA - Group for Artificial Intelligence Applications 006 * http://gaia.fdi.ucm.es 007 * 03/01/2007 008 */ 009 package jcolibri.util; 010 011 import java.io.File; 012 import java.io.InputStream; 013 import java.net.MalformedURLException; 014 import java.net.URL; 015 016 /** 017 * Utility functions to transparently access to files in the file system, jar file, classpath... 018 * @author Juan A. Recio-Garcia 019 * @version 1.0 020 */ 021 public class FileIO { 022 023 /** 024 * Returns the URL that localizes a file. It tries the following locations: 025 * <ul> 026 * <li>The path recieved by parameter 027 * <li>"bin/"+path 028 * <li>"src/"+path 029 * <li>"/"+path 030 * <li>path inside a jar 031 * <li>"/"+path inside a jar 032 * </ul> 033 */ 034 @SuppressWarnings("deprecation") 035 public static URL findFile(String file) 036 { 037 038 File f; 039 040 try { 041 f = new File(file); 042 if(f.exists()) 043 return f.toURL(); 044 } catch (MalformedURLException e1) {} 045 046 try { 047 f = new File("bin/"+file); 048 if(f.exists()) 049 return f.toURL(); 050 } catch (MalformedURLException e1) {} 051 052 try { 053 f = new File("src/"+file); 054 if(f.exists()) 055 return f.toURL(); 056 } catch (MalformedURLException e1) {} 057 058 file = file.replace('\\','/'); 059 try { 060 URL url = FileIO.class.getResource(file); 061 if(url!= null) 062 return url; 063 } catch (Exception e) {} 064 065 try { 066 URL url = FileIO.class.getResource("/"+file); 067 if(url!= null) 068 return url; 069 } catch (Exception e) {} 070 071 org.apache.commons.logging.LogFactory.getLog(FileIO.class).warn("File not found: "+file); 072 return null; 073 } 074 075 /** 076 * Tries to return an input stream of the file 077 */ 078 public static InputStream openFile(String file) 079 { 080 URL url = null; 081 try 082 { 083 url = new URL(file); 084 return url.openStream(); 085 }catch(Exception e) {} 086 087 url = findFile(file); 088 try 089 { 090 return url.openStream(); 091 }catch(Exception e) {} 092 093 file = file.replace('\\','/'); 094 file = file.substring(file.indexOf('!')+1); 095 try { 096 return FileIO.class.getResourceAsStream(file); 097 } catch (Exception e) {} 098 099 try { 100 return FileIO.class.getResourceAsStream("/"+file); 101 } catch (Exception e) {} 102 103 org.apache.commons.logging.LogFactory.getLog(FileIO.class).warn("Error opening stream for: "+file); 104 return null; 105 } 106 }