View Javadoc

1   package es.inteco.eni.utils;
2   
3   import java.io.BufferedReader;
4   import java.io.BufferedWriter;
5   import java.io.File;
6   import java.io.FileInputStream;
7   import java.io.FileOutputStream;
8   import java.io.IOException;
9   import java.io.InputStreamReader;
10  import java.io.OutputStreamWriter;
11  import java.io.PrintWriter;
12  import java.nio.charset.Charset;
13  import java.util.ArrayList;
14  import java.util.List;
15  
16  import org.apache.commons.codec.binary.Base64;
17  
18  
19  /**
20   * Clase de utilidad para la gestión de ficheros
21   * 
22   *
23   */
24  public final class FileUtils {
25  
26  	/**
27  	 * Extension de los ficheros XML
28  	 */
29  	public static final String XML_EXTENSION = "xml";
30  
31  	/**
32  	 * Extension de los schemas XSD
33  	 */
34  	private static final String XSD_EXTENSION = "xsd";
35  
36  	/**
37  	 * Número de caracteres del buffer para lectura de un fichero
38  	 */
39  	private static final int BUFFER_CHARS_NUMBER = 1024;
40  
41  	/**
42  	 * Número de bytes del buffer para lectura 
43  	 */
44  	private static final int BUFFER_BYTES_NUMBER = 4096;
45  
46  
47  	/**
48  	 * Constructor privado, no se puede instanciar
49  	 */
50  	private FileUtils(){
51  
52  	}
53  
54  
55  	/**
56  	 * Devuelve la lista de ficheros existentes en una carpeta
57  	 * @param folder Carpeta
58  	 * @return lista de ficheros existentes en una carpeta
59  	 */
60  	public static List<File> getXsdFilesInFolder(File folder){
61  		return getFilesInFolder(folder, XSD_EXTENSION);
62  	}
63  
64  	/**
65  	 * Lectura de un fichero
66  	 * @param filePath Ruta del fichero a leer
67  	 * @return String con el contenido del fichero
68  	 * @throws IOException 
69  	 * @throws IOException Error en la lectura
70  	 */
71  	public static String readFileAsString(String filePath) throws IOException{
72  		if(filePath==null || !new File(filePath).exists()){
73  			return null;
74  		}
75  		StringBuffer fileData = new StringBuffer();
76  		BufferedReader reader = null;
77  		try{
78  			reader = new BufferedReader( new InputStreamReader(
79  					new FileInputStream(filePath),
80  					Charset.forName("UTF-8")));
81  
82  			char[] buf = new char[BUFFER_CHARS_NUMBER];
83  
84  			int numRead=0;
85  			while((numRead=reader.read(buf)) != -1){
86  				fileData.append(buf, 0, numRead);
87  			}
88  		}finally{
89  			if(reader!=null){
90  				reader.close();
91  			}
92  		}
93  
94  		return fileData.toString();
95  	}
96  
97  
98  	/**
99  	 * Devuelve la lista de ficheros existentes en una carpeta con una determina extensión
100 	 * @param folder Carpeta
101 	 * @param extension Extension
102 	 * @return lista de ficheros existentes en una carpeta con una determina extensión
103 	 */
104 	private static List<File> getFilesInFolder(File folder, String extension){
105 		List<File> result = new ArrayList<File>();
106 		//Comprobamos que el fichero existe y que es un directorio
107 		boolean notExistFolder =folder==null || !folder.exists() || folder.isFile();
108 		if(notExistFolder){
109 			return result;
110 		}
111 		//Lista de ficheros de un directorio
112 		File[] listFiles = folder.listFiles();
113 		for (int i=0; listFiles!=null && i<listFiles.length; i++){
114 			File file = listFiles[i];
115 			String fileExtension = getFileExtension(file);
116 			boolean isSearchedFile = file.isFile() && (extension==null || extension.toUpperCase().equals(fileExtension.toUpperCase()));
117 			if (isSearchedFile){
118 				result.add(file);
119 			}else if (file.isDirectory()&& !file.isHidden()){
120 				List<File> folderFiles = getFilesInFolder(file, extension);
121 				if (folderFiles!=null && folderFiles.size()>0){
122 					result.addAll(folderFiles);
123 				}
124 			}
125 		}
126 		return result;
127 	}
128 
129 	/**
130 	 * Extension de un fichero
131 	 * @param file Fichero
132 	 * @return Extension de un fichero
133 	 */
134 	public static String getFileExtension(File file){
135 		String fileName = file.getName();
136 		return fileName.indexOf('.')!=-1 ? fileName.substring(fileName.lastIndexOf('.')+1) : null;
137 
138 	}
139 
140 	/**
141 	 * Escribe una cadena de texto en un fichero
142 	 * @param file Fichero
143 	 * @param dataString Cadena de texto
144 	 * @throws IOException
145 	 */
146 	public static void writeFile(File file, String dataString) throws IOException {
147 		PrintWriter out = null;
148 		try {
149 			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8")));
150 			out.print (dataString);
151 			out.flush ();
152 		}
153 		finally{
154 			if(out!=null){
155 				out.close ();
156 			}
157 		}
158 	}
159 
160 
161 	/**
162 	 * Escribe y devuelve los bytes en un fichero temporal
163 	 * @param byteContent Contenido del fichero
164 	 * @return Fichero temporal con los bytes escirtos
165 	 * @throws IOException
166 	 */
167 	public static File getTempFileFromBytes(String extension, byte[] byteContent) throws IOException {
168 		FileOutputStream  fos = null;
169 		File tempFile = File.createTempFile(System.nanoTime()+"", extension==null || "".equals(extension) ? "" : "."+extension);
170 		try {
171 			fos = new FileOutputStream(tempFile);
172 			fos.write(byteContent);
173 		}finally{
174 			fos.close();
175 		}
176 
177 		return tempFile;
178 	}
179 
180 	/**
181 	 * Escribe y devuelve un fichero temporal a partir de una cadena de texto en base64 decodificada
182 	 * @param extension Extension del fichero
183 	 * @param base64Str Cadena de texto codificada en Base64
184 	 * @return Fichero temporal a partir de una cadena de texto en base64 decodificada
185 	 * @throws IOException 
186 	 */
187 	public static File getTempFileFromBase64String(String extension,String base64Str) throws IOException{
188 		return getTempFileFromBytes(extension, Base64.decodeBase64(base64Str));
189 	}
190 
191 
192 	/**
193 	 * Copia un fichero a una nueva ruta
194 	 * @param fromFile Fichero origen
195 	 * @param toFile Fichero destino
196 	 * @throws IOException Excepcion
197 	 */
198 	public static void copy(File fromFile, File toFile)throws IOException {
199 
200 		//Comprobaciones
201 		if (!fromFile.exists()){
202 			throw new IOException("No existe el fichero: " + fromFile.getAbsolutePath());
203 		}
204 		if (!fromFile.isFile()){
205 			throw new IOException("No se puede copiar el directorio: " + fromFile.getAbsolutePath());
206 		}
207 		if (!fromFile.canRead()){
208 			throw new IOException("No se puede leer el fichero : " + fromFile.getAbsolutePath());
209 		}
210 		if (toFile.isDirectory()){
211 			toFile = new File(toFile, fromFile.getName());
212 		}
213 		if (toFile.exists()) {
214 			if (!toFile.canWrite()){
215 				throw new IOException("No se puede sobreescribir el fichero : " + toFile.getAbsolutePath());
216 			}
217 		} else {
218 			String parent = toFile.getParent();
219 			if (parent == null){
220 				parent = System.getProperty("user.dir");
221 			}
222 			File dir = new File(parent);
223 			if (!dir.exists()){
224 				throw new IOException("El directorio: " + parent + " de destino del fichero no existe");
225 			}
226 			if (dir.isFile()){
227 				throw new IOException("El destino: " + parent + " no es un directorio");
228 			}
229 			if (!dir.canWrite())
230 				throw new IOException("No se puede escribir el fichero en el directorio: " + parent );
231 		}
232 
233 		//Copia el fichero
234 		FileInputStream from = null;
235 		FileOutputStream to = null;
236 		try {
237 			from = new FileInputStream(fromFile);
238 			to = new FileOutputStream(toFile);
239 			byte[] buffer = new byte[BUFFER_BYTES_NUMBER];
240 			int bytesRead;
241 
242 			while ((bytesRead = from.read(buffer)) != -1){
243 				to.write(buffer, 0, bytesRead); 
244 			}
245 		} finally {
246 			if (from != null){
247 				from.close();
248 			}
249 			if (to != null){
250 				to.close();
251 			}
252 		}
253 	}
254 }