gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.lib / org.gvsig.raster.lib.impl / src / main / java / org / gvsig / raster / util / DefaultFileUtils.java @ 965
History | View | Annotate | Download (14.1 KB)
1 |
/* gvSIG. Geographic Information System of the Valencian Government
|
---|---|
2 |
*
|
3 |
* Copyright (C) 2007-2008 Infrastructures and Transports Department
|
4 |
* of the Valencian Government (CIT)
|
5 |
*
|
6 |
* This program is free software; you can redistribute it and/or
|
7 |
* modify it under the terms of the GNU General Public License
|
8 |
* as published by the Free Software Foundation; either version 2
|
9 |
* of the License, or (at your option) any later version.
|
10 |
*
|
11 |
* This program is distributed in the hope that it will be useful,
|
12 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
14 |
* GNU General Public License for more details.
|
15 |
*
|
16 |
* You should have received a copy of the GNU General Public License
|
17 |
* along with this program; if not, write to the Free Software
|
18 |
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
19 |
* MA 02110-1301, USA.
|
20 |
*
|
21 |
*/
|
22 |
package org.gvsig.raster.util; |
23 |
|
24 |
import java.awt.geom.AffineTransform; |
25 |
import java.io.BufferedOutputStream; |
26 |
import java.io.BufferedReader; |
27 |
import java.io.DataOutputStream; |
28 |
import java.io.File; |
29 |
import java.io.FileInputStream; |
30 |
import java.io.FileNotFoundException; |
31 |
import java.io.FileOutputStream; |
32 |
import java.io.FileReader; |
33 |
import java.io.IOException; |
34 |
import java.io.InputStream; |
35 |
import java.io.OutputStream; |
36 |
import java.text.NumberFormat; |
37 |
import java.util.ArrayList; |
38 |
|
39 |
import org.gvsig.fmap.dal.coverage.datastruct.Extent; |
40 |
import org.gvsig.fmap.dal.coverage.util.FileUtils; |
41 |
import org.gvsig.fmap.dal.coverage.util.PropertyEvent; |
42 |
import org.gvsig.fmap.dal.coverage.util.PropertyListener; |
43 |
|
44 |
|
45 |
/**
|
46 |
* Utilities for files, directories and file names
|
47 |
*
|
48 |
* @author Nacho Brodin (nachobrodin@gmail.com)
|
49 |
*/
|
50 |
public class DefaultFileUtils implements FileUtils { |
51 |
/**
|
52 |
* Copia de ficheros
|
53 |
* @param pathOrig Ruta de origen
|
54 |
* @param pathDst Ruta de destino.
|
55 |
*/
|
56 |
public void copyFile(String pathOrig, String pathDst) throws FileNotFoundException, IOException { |
57 |
InputStream in;
|
58 |
OutputStream out;
|
59 |
|
60 |
if (pathOrig == null || pathDst == null) { |
61 |
System.err.println("Error en path"); |
62 |
return;
|
63 |
} |
64 |
|
65 |
File orig = new File(pathOrig); |
66 |
if (!orig.exists() || !orig.isFile() || !orig.canRead()) {
|
67 |
System.err.println("Error copying the file:" + pathOrig + " <Source Exists:" + orig.exists() + ", Source is file:" + orig.isFile() + ", Source can be read:" + orig.canRead() + ">"); |
68 |
return;
|
69 |
} |
70 |
|
71 |
File dest = new File(pathDst); |
72 |
String file = new File(pathOrig).getName(); |
73 |
if (dest.isDirectory())
|
74 |
pathDst += file; |
75 |
|
76 |
dest = new File(pathDst); |
77 |
if(!dest.exists())
|
78 |
dest.createNewFile(); |
79 |
|
80 |
in = new FileInputStream(pathOrig); |
81 |
out = new FileOutputStream(pathDst); |
82 |
|
83 |
byte[] buf = new byte[1024]; |
84 |
int len;
|
85 |
|
86 |
while ((len = in.read(buf)) > 0) |
87 |
out.write(buf, 0, len);
|
88 |
|
89 |
in.close(); |
90 |
out.close(); |
91 |
} |
92 |
|
93 |
/**
|
94 |
* Crea un fichero de georeferenciaci?n (world file) para un dataset
|
95 |
* determinado
|
96 |
* @param fileName Nombre completo del fichero de raster
|
97 |
* @param Extent
|
98 |
* @param pxWidth Ancho en p?xeles
|
99 |
* @param pxHeight Alto en p?xeles
|
100 |
* @return
|
101 |
* @throws IOException
|
102 |
*/
|
103 |
public void createWorldFile(String fileName, Extent ext, int pxWidth, int pxHeight) throws IOException { |
104 |
File tfw = null; |
105 |
|
106 |
String extWorldFile = ".wld"; |
107 |
if (fileName.endsWith("tif")) |
108 |
extWorldFile = ".tfw";
|
109 |
if (fileName.endsWith("jpg") || fileName.endsWith("jpeg")) |
110 |
extWorldFile = ".jpgw";
|
111 |
|
112 |
tfw = new File(fileName.substring(0, fileName.lastIndexOf(".")) + extWorldFile); |
113 |
|
114 |
// Generamos un world file para gdal
|
115 |
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tfw))); |
116 |
dos.writeBytes((ext.getMax().getX() - ext.getMin().getX()) / (pxWidth - 1) + "\n"); |
117 |
dos.writeBytes("0.0\n");
|
118 |
dos.writeBytes("0.0\n");
|
119 |
dos.writeBytes((ext.getMin().getY() - ext.getMax().getY()) / (pxHeight - 1) + "\n"); |
120 |
dos.writeBytes("" + ext.getMin().getX() + "\n"); |
121 |
dos.writeBytes("" + ext.getMax().getY() + "\n"); |
122 |
dos.close(); |
123 |
} |
124 |
|
125 |
/**
|
126 |
* Crea un fichero de georeferenciaci?n (world file) para un dataset
|
127 |
* determinado
|
128 |
* @param fileName Nombre completo del fichero de raster
|
129 |
* @param AffineTransform
|
130 |
* @param pxWidth Ancho en p?xeles
|
131 |
* @param pxHeight Alto en p?xeles
|
132 |
* @return
|
133 |
* @throws IOException
|
134 |
*/
|
135 |
public void createWorldFile(String fileName, AffineTransform at, int pxWidth, int pxHeight) throws IOException { |
136 |
File tfw = null; |
137 |
|
138 |
String extWorldFile = ".wld"; |
139 |
if (fileName.endsWith("tif")) |
140 |
extWorldFile = ".tfw";
|
141 |
if (fileName.endsWith("jpg") || fileName.endsWith("jpeg")) |
142 |
extWorldFile = ".jpgw";
|
143 |
|
144 |
tfw = new File(fileName.substring(0, fileName.lastIndexOf(".")) + extWorldFile); |
145 |
|
146 |
// Generamos un world file para gdal
|
147 |
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tfw))); |
148 |
dos.writeBytes(at.getScaleX() + "\n");
|
149 |
dos.writeBytes(at.getShearX() + "\n");
|
150 |
dos.writeBytes(at.getShearY() + "\n");
|
151 |
dos.writeBytes(at.getScaleY() + "\n");
|
152 |
dos.writeBytes("" + at.getTranslateX() + "\n"); |
153 |
dos.writeBytes("" + at.getTranslateY() + "\n"); |
154 |
dos.close(); |
155 |
} |
156 |
|
157 |
/**
|
158 |
* Formatea en forma de cadena un tama?o dado en bytes. El resultado ser? una
|
159 |
* cadena con GB, MB, KB y B
|
160 |
* @param size tama?o a formatear
|
161 |
* @return cadena con la cantidad formateada
|
162 |
*/
|
163 |
public String formatFileSize(long size) { |
164 |
double bytes = size;
|
165 |
double kBytes = 0.0; |
166 |
double mBytes = 0.0; |
167 |
double gBytes = 0.0; |
168 |
if (bytes >= 1024.0) { |
169 |
kBytes = bytes / 1024.0;
|
170 |
if (kBytes >= 1024.0) { |
171 |
mBytes = kBytes / 1024.0;
|
172 |
if (mBytes >= 1024.0) |
173 |
gBytes = mBytes / 1024.0;
|
174 |
} |
175 |
} |
176 |
|
177 |
String texto = ""; |
178 |
NumberFormat numberFormat = NumberFormat.getNumberInstance(); |
179 |
numberFormat.setMinimumFractionDigits(0);
|
180 |
|
181 |
do {
|
182 |
if (gBytes > 0) { |
183 |
numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(gBytes)); |
184 |
texto = numberFormat.format(gBytes) + " GB";
|
185 |
break;
|
186 |
} |
187 |
if (mBytes > 0) { |
188 |
numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(mBytes)); |
189 |
texto = numberFormat.format(mBytes) + " MB";
|
190 |
break;
|
191 |
} |
192 |
if (kBytes > 0) { |
193 |
numberFormat.setMaximumFractionDigits(2 - (int) Math.log10(kBytes)); |
194 |
texto = numberFormat.format(kBytes) + " KB";
|
195 |
break;
|
196 |
} |
197 |
if (bytes != 0) { |
198 |
numberFormat.setMaximumFractionDigits(0);
|
199 |
texto = numberFormat.format(bytes) + " bytes";
|
200 |
break;
|
201 |
} |
202 |
} while (false); |
203 |
|
204 |
numberFormat.setMaximumFractionDigits(0);
|
205 |
|
206 |
return texto + " (" + numberFormat.format(bytes) + " bytes)"; |
207 |
} |
208 |
|
209 |
/**
|
210 |
* Obtiene la extensi?n del fichero a partir de su nombre.
|
211 |
* @param file Nombre o ruta del fichero
|
212 |
* @return Cadena con la extensi?n que representa el tipo de fichero. Devuelve
|
213 |
* null si no tiene extension.
|
214 |
*/
|
215 |
public String getExtensionFromFileName(String file) { |
216 |
return file.substring(file.lastIndexOf(".") + 1).toLowerCase(); |
217 |
} |
218 |
|
219 |
/**
|
220 |
* Obtiene el nombre de fichero sin la extensi?n.
|
221 |
* @param file Nombre o ruta del fichero
|
222 |
* @return Cadena con la extensi?n que representa el tipo de fichero. Si no
|
223 |
* tiene extensi?n devuelve el mismo fichero de entrada
|
224 |
*/
|
225 |
public String getNameWithoutExtension(String file) { |
226 |
if (file == null) |
227 |
return null; |
228 |
|
229 |
int n = file.lastIndexOf("."); |
230 |
if (n != -1) |
231 |
return file.substring(0, n); |
232 |
return file;
|
233 |
} |
234 |
|
235 |
/**
|
236 |
* Obtiene el nombre de fichero sin la extensi?n ni la ruta.
|
237 |
* @param file Ruta del fichero
|
238 |
* @return Cadena que representa el nombre del fichero sin extensi?n ni path de directorios
|
239 |
*/
|
240 |
public String getFileNameFromCanonical(String file) { |
241 |
if (file == null) |
242 |
return null; |
243 |
|
244 |
int n = file.lastIndexOf("."); |
245 |
if (n != -1) |
246 |
file = file.substring(0, n);
|
247 |
|
248 |
n = file.lastIndexOf(File.separator);
|
249 |
if(n != -1) |
250 |
file = file.substring(n + 1, file.length());
|
251 |
|
252 |
return file;
|
253 |
} |
254 |
|
255 |
/**
|
256 |
* Obtiene el ?ltimo trozo de la cadena a partir de los caracteres que
|
257 |
* coincidan con el patr?n. En caso de que el patr?n no exista en la cadena
|
258 |
* devuelve esta completa
|
259 |
* @param string
|
260 |
* @param pattern
|
261 |
* @return
|
262 |
*/
|
263 |
public String getLastPart(String string, String pattern) { |
264 |
int n = string.lastIndexOf(pattern);
|
265 |
if (n > 0) |
266 |
return string.substring(n + 1, string.length()); |
267 |
return string;
|
268 |
} |
269 |
|
270 |
/**
|
271 |
* Obtiene la codificaci?n de un fichero XML
|
272 |
* @param file Nombre del fichero XML
|
273 |
* @return Codificaci?n
|
274 |
*/
|
275 |
public String readFileEncoding(String file) { |
276 |
FileReader fr;
|
277 |
String encoding = null; |
278 |
try {
|
279 |
fr = new FileReader(file); |
280 |
BufferedReader br = new BufferedReader(fr); |
281 |
char[] buffer = new char[100]; |
282 |
br.read(buffer); |
283 |
StringBuffer st = new StringBuffer(new String(buffer)); |
284 |
String searchText = "encoding=\""; |
285 |
int index = st.indexOf(searchText);
|
286 |
if (index > -1) { |
287 |
st.delete(0, index + searchText.length());
|
288 |
encoding = st.substring(0, st.indexOf("\"")); |
289 |
} |
290 |
fr.close(); |
291 |
} catch (FileNotFoundException ex) { |
292 |
ex.printStackTrace(); |
293 |
} catch (IOException e) { |
294 |
e.printStackTrace(); |
295 |
} |
296 |
return encoding;
|
297 |
} |
298 |
|
299 |
/**
|
300 |
* Obtiene el nombre del fichero RMF a partir del nombre del fichero. Si el
|
301 |
* nombre del fichero tiene una extensi?n esta llamada sustituir? la extensi?n
|
302 |
* existente por .rmf. Si el fichero pasado no tiene extensi?n esta llamada
|
303 |
* a?adir? .rm al final.
|
304 |
* @param fileName Nombre del fichero raster de origen
|
305 |
* @return Nombre del fichero rmf asociado al raster.
|
306 |
*/
|
307 |
public String getRMFNameFromFileName(String fileName) { |
308 |
return getNameWithoutExtension(fileName) + ".rmf"; |
309 |
} |
310 |
|
311 |
/**
|
312 |
* Recursive directory delete.
|
313 |
* @param f
|
314 |
*/
|
315 |
private void deleteDirectory(File f) { |
316 |
File[] files = f.listFiles(); |
317 |
for (int i = 0; i < files.length; i++) { |
318 |
if (files[i].isDirectory())
|
319 |
deleteDirectory(files[i]); |
320 |
files[i].delete(); |
321 |
} |
322 |
} |
323 |
|
324 |
//******* Servicio de directorios temporales **************
|
325 |
|
326 |
/**
|
327 |
* Directorio temporal para la cach?. Si gastamos el mismo que andami este se ocupar? de gestionar su
|
328 |
* destrucci?n al cerrar gvSIG.
|
329 |
*/
|
330 |
private String tempCacheDirectoryPath = System.getProperty("java.io.tmpdir") |
331 |
+ File.separator + "tmp-andami"; |
332 |
|
333 |
/**
|
334 |
* Elimina los ficheros del directorio temporal. Realizamos esta acci?n al
|
335 |
* levantar la librer?a.
|
336 |
*/
|
337 |
public void cleanUpTempFiles() { |
338 |
try {
|
339 |
File tempDirectory = new File(tempCacheDirectoryPath); |
340 |
|
341 |
File[] files = tempDirectory.listFiles(); |
342 |
if (files != null) |
343 |
for (int i = 0; i < files.length; i++) { |
344 |
// s?lo por si en un futuro se necesitan crear directorios temporales
|
345 |
if (files[i].isDirectory())
|
346 |
deleteDirectory(files[i]); |
347 |
files[i].delete(); |
348 |
} |
349 |
tempDirectory.delete(); |
350 |
} catch (Exception e) { |
351 |
} |
352 |
} |
353 |
|
354 |
/**
|
355 |
* Esta funci?n crea el directorio para temporales y devuelve el manejador
|
356 |
* del directorio
|
357 |
* @return
|
358 |
*/
|
359 |
public File getTemporalFile() { |
360 |
File tempDirectory = new File(tempCacheDirectoryPath); |
361 |
if (!tempDirectory.exists())
|
362 |
tempDirectory.mkdir(); |
363 |
return tempDirectory;
|
364 |
} |
365 |
|
366 |
/**
|
367 |
* Esta funci?n crea el directorio para temporales y devuelve la ruta de este
|
368 |
* @return
|
369 |
*/
|
370 |
public String getTemporalPath() { |
371 |
return getTemporalFile().getAbsolutePath();
|
372 |
} |
373 |
|
374 |
/*
|
375 |
* (non-Javadoc)
|
376 |
* @see org.gvsig.fmap.dal.coverage.util.FileUtils#getFormatedRasterFileName(java.lang.String)
|
377 |
*/
|
378 |
public String getFormatedRasterFileName(String name) { |
379 |
if(name.startsWith("PG:host=")) { |
380 |
String newName = ""; |
381 |
String schema = null; |
382 |
String table = null; |
383 |
int index = name.indexOf(" schema='") + 8; |
384 |
if(index != -1) { |
385 |
try {
|
386 |
schema = name.substring(index + 1, name.indexOf("'", index + 1)); |
387 |
newName += schema + ".";
|
388 |
} catch (StringIndexOutOfBoundsException e) { |
389 |
} |
390 |
} |
391 |
index = name.indexOf(" table='") + 7; |
392 |
if(index != -1) { |
393 |
try {
|
394 |
table = name.substring(index + 1, name.indexOf("'", index + 1)); |
395 |
newName += table; |
396 |
} catch (StringIndexOutOfBoundsException e) { |
397 |
} |
398 |
} |
399 |
return newName;
|
400 |
} |
401 |
return name;
|
402 |
} |
403 |
|
404 |
//******* Servicio de nombres de capas ?nicos **************
|
405 |
/**
|
406 |
* Contador global de las capas generadas para raster. Hay que contar con que esta
|
407 |
* clase es un singleton desde el manager. Si hay varias instanciaciones layerCount
|
408 |
* dar? valores erroneos.
|
409 |
*/
|
410 |
private int layerCount = 1; |
411 |
private ArrayList<PropertyListener> |
412 |
propetiesListeners = new ArrayList<PropertyListener>(); |
413 |
|
414 |
/**
|
415 |
* La gesti?n de nombres ?nicos en la generaci?n de capas se lleva de forma
|
416 |
* autom?tica. Cuando alguien crea una capa nueva, si esta no tiene nombre especifico,
|
417 |
* obtiene su nombre mediante este m?todo. La siguiente vez que se llame dar? un nombre
|
418 |
* distinto. El nombre de la capa ser? NewLayer_ seguido de un contador de actualizaci?n
|
419 |
* autom?tica cada vez que se usa.
|
420 |
* @return Nombre ?nico para la capa.
|
421 |
*/
|
422 |
public String usesOnlyLayerName() { |
423 |
String oldValue = getOnlyLayerName();
|
424 |
String newValue = "NewLayer_" + (++layerCount); |
425 |
for (int i = 0; i < propetiesListeners.size(); i++) |
426 |
if(propetiesListeners.get(i) instanceof PropertyListener) |
427 |
((PropertyListener)propetiesListeners.get(i)).actionValueChanged(new PropertyEvent(oldValue, "NewLayer", newValue, oldValue)); |
428 |
return newValue;
|
429 |
} |
430 |
|
431 |
/**
|
432 |
* Obtiene el nombre ?nico de la siguiente capa sin actualizar el contador. Es
|
433 |
* solo para consulta. La siguiente vez que se llama a getOnlyLayerName o usesOnlyLayerName
|
434 |
* devolver? el mismo nomnbre.
|
435 |
* @return Nombre ?nico para la capa.
|
436 |
*/
|
437 |
public String getOnlyLayerName() { |
438 |
return "NewLayer_" + layerCount; |
439 |
} |
440 |
|
441 |
/**
|
442 |
* A?adir un listener a la lista de eventos
|
443 |
* @param listener
|
444 |
*/
|
445 |
public void addOnlyLayerNameListener(PropertyListener listener) { |
446 |
if (!propetiesListeners.contains(listener))
|
447 |
propetiesListeners.add(listener); |
448 |
} |
449 |
|
450 |
/**
|
451 |
* Elimina un listener de la lista de eventos
|
452 |
* @param listener
|
453 |
*/
|
454 |
public void removeOnlyLayerNameListener(PropertyListener listener) { |
455 |
for (int i = 0; i < propetiesListeners.size(); i++) |
456 |
if(propetiesListeners.get(i) == listener)
|
457 |
propetiesListeners.remove(i); |
458 |
} |
459 |
|
460 |
//******* End: Servicio de nombres de capas ?nicos **************
|
461 |
} |