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