1 34 package net.myvietnam.mvncore.util; 35 36 import java.io.*; 37 import java.net.URL ; 38 import java.text.DecimalFormat ; 39 40 import net.myvietnam.mvncore.exception.BadInputException; 41 import net.myvietnam.mvncore.filter.DisableHtmlTagFilter; 42 import org.apache.commons.logging.Log; 43 import org.apache.commons.logging.LogFactory; 44 45 public final class FileUtil { 46 47 private static Log log = LogFactory.getLog(FileUtil.class); 48 49 private static FileUtil instance = new FileUtil(); 50 51 private static String servletClassesPath = null; 52 53 private FileUtil() { } 55 56 public static void checkGoodFilePath(String str) throws BadInputException { 57 byte[] s = str.getBytes(); 58 int length = s.length; 59 byte b = 0; 60 61 for (int i = 0; i < length; i++) { 62 b = s[i]; 63 if ((b == '*') || 64 (b == '?') || 65 (b == '<') || 66 (b == '>') || 67 (b == '"') || 68 (b == '|') || 69 (b == '\0')) { throw new BadInputException("The string '" + DisableHtmlTagFilter.filter(str) + "' is not a good file path. Reason: character '" + (char)(b) + "' is not allowed."); 73 } 74 } } 76 77 public static void checkGoodFileName(String str) throws BadInputException { 78 checkGoodFilePath(str); 80 byte[] s = str.getBytes(); 81 int length = s.length; 82 byte b = 0; 83 84 for (int i = 0; i < length; i++) { 85 b = s[i]; 86 if ((b == '/') || 87 (b == '\\') || 88 (b == ':')) { 89 throw new BadInputException("The string '" + DisableHtmlTagFilter.filter(str) + "' is not a good file name. Reason: character '" + (char)(b) + "' is not allowed."); 92 } 93 } } 95 96 public static void createDir(String dir, boolean ignoreIfExitst) throws IOException { 97 File file = new File(dir); 98 99 if (ignoreIfExitst && file.exists()) { 100 return; 101 } 102 103 if ( file.mkdir() == false) { 104 throw new IOException("Cannot create the directory = " + dir); 105 } 106 } 107 108 public static void createDirs(String dir, boolean ignoreIfExitst) throws IOException { 109 File file = new File(dir); 110 111 if (ignoreIfExitst && file.exists()) { 112 return; 113 } 114 115 if ( file.mkdirs() == false) { 116 throw new IOException("Cannot create directories = " + dir); 117 } 118 } 119 120 public static void deleteFile(String filename) throws IOException { 121 File file = new File(filename); 122 log.trace("Delete file = " + filename); 123 if (file.isDirectory()) { 124 throw new IOException("IOException -> BadInputException: not a file."); 125 } 126 if (file.exists() == false) { 127 throw new IOException("IOException -> BadInputException: file is not exist."); 128 } 129 if (file.delete() == false) { 130 throw new IOException("Cannot delete file. filename = " + filename); 131 } 132 } 133 134 public static void deleteDir(File dir) throws IOException { 135 if (dir.isFile()) throw new IOException("IOException -> BadInputException: not a directory."); 136 File[] files = dir.listFiles(); 137 if (files != null) { 138 for (int i = 0; i < files.length; i++) { 139 File file = files[i]; 140 if (file.isFile()) { 141 file.delete(); 142 } else { 143 deleteDir(file); 144 } 145 } 146 } dir.delete(); 148 } 149 150 public static long getDirLength(File dir) throws IOException { 151 if (dir.isFile()) throw new IOException("BadInputException: not a directory."); 152 long size = 0; 153 File[] files = dir.listFiles(); 154 if (files != null) { 155 for (int i = 0; i < files.length; i++) { 156 File file = files[i]; 157 long length = 0; 158 if (file.isFile()) { 159 length = file.length(); 160 } else { 161 length = getDirLength(file); 162 } 163 size += length; 164 } } return size; 167 } 168 169 public static long getDirLength_onDisk(File dir) throws IOException { 170 if (dir.isFile()) throw new IOException("BadInputException: not a directory."); 171 long size = 0; 172 File[] files = dir.listFiles(); 173 if (files != null) { 174 for (int i = 0; i < files.length; i++) { 175 File file = files[i]; 176 long length = 0; 177 if (file.isFile()) { 178 length = file.length(); 179 } else { 180 length = getDirLength_onDisk(file); 181 } 182 double mod = Math.ceil(((double)length)/512); 183 if (mod == 0) mod = 1; 184 length = ((long)mod) * 512; 185 size += length; 186 } 187 } return size; 189 } 190 191 public static void emptyFile(String srcFilename) throws IOException { 192 File srcFile = new File(srcFilename); 193 if (!srcFile.exists()) { 194 throw new FileNotFoundException("Cannot find the file: " + srcFile.getAbsolutePath()); 195 } 196 if (!srcFile.canWrite()) { 197 throw new IOException("Cannot write the file: " + srcFile.getAbsolutePath()); 198 } 199 200 FileOutputStream outputStream = new FileOutputStream(srcFilename); 201 outputStream.close(); 202 } 203 204 public static void copyFile(String srcFilename, String destFilename, boolean overwrite) throws IOException { 205 206 File srcFile = new File(srcFilename); 207 if (!srcFile.exists()) { 208 throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath()); 209 } 210 if (!srcFile.canRead()) { 211 throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath()); 212 } 213 214 File destFile = new File(destFilename); 215 if (overwrite == false) { 216 if (destFile.exists()) return; 217 } else { 218 if (destFile.exists()) { 219 if (!destFile.canWrite()) { 220 throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath()); 221 } 222 } else { 223 if (!destFile.createNewFile()) { 224 throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath()); 225 } 226 } 227 } 228 229 BufferedInputStream inputStream = null; 230 BufferedOutputStream outputStream = null; 231 byte[] block = new byte[1024]; 232 try { 233 inputStream = new BufferedInputStream(new FileInputStream(srcFile)); 234 outputStream = new BufferedOutputStream(new FileOutputStream(destFile)); 235 while (true) { 236 int readLength = inputStream.read(block); 237 if (readLength == -1) break; outputStream.write(block, 0, readLength); 239 } 240 } finally { 241 if (inputStream != null) { 242 try { 243 inputStream.close(); 244 } catch (IOException ex) { 245 } 247 } 248 if (outputStream != null) { 249 try { 250 outputStream.close(); 251 } catch (IOException ex) { 252 } 254 } 255 } 256 } 257 258 public static byte[] getBytes(InputStream inputStream) throws IOException { 260 BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); 261 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024); 262 byte[] block = new byte[4096]; 263 while (true) { 264 int readLength = bufferedInputStream.read(block); 265 if (readLength == -1) break; byteArrayOutputStream.write(block, 0, readLength); 267 } 268 byte[] retValue = byteArrayOutputStream.toByteArray(); 269 byteArrayOutputStream.close(); 270 return retValue; 271 } 272 273 public static String getFileName(String fullFilePath) { 274 if (fullFilePath == null) { 275 return ""; 276 } 277 int index1 = fullFilePath.lastIndexOf('/'); 278 int index2 = fullFilePath.lastIndexOf('\\'); 279 280 int index = (index1 > index2) ? index1 : index2; 282 if (index == -1) { 283 return fullFilePath; 285 } 286 String fileName = fullFilePath.substring(index + 1); 287 return fileName; 288 } 289 290 296 public static void popFile(File srcFile, OutputStream output) throws IOException { 297 298 BufferedInputStream input = null; 299 byte[] block = new byte[4096]; 300 try { 301 input = new BufferedInputStream(new FileInputStream(srcFile), 4096); 302 while (true) { 303 int length = input.read(block); 304 if (length == -1) break; output.write(block, 0, length); 306 } 307 } finally { 308 if (input != null) { 309 try { 310 input.close(); 311 } catch (IOException ex) { 312 } 314 } 315 } 316 } 317 318 323 public static void setServletClassesPath(String path) { 324 log.debug("FileUtil.setServletClassesPath called with path = " + path); 325 326 servletClassesPath = path; 327 328 if (servletClassesPath == null) { 329 return; 332 } 333 if (servletClassesPath.endsWith(File.separator) == false) { 334 servletClassesPath = servletClassesPath + File.separatorChar; 335 log.debug("FileUtil.setServletClassesPath change path to value = " + servletClassesPath); 336 } 337 } 338 339 346 public static String getServletClassesPath() { 347 if (servletClassesPath == null) { 348 String strPath = System.getProperty("mvncore.context.path"); 349 if (strPath != null && (strPath.length() > 0)) { 350 servletClassesPath = strPath; 351 } else { 352 ClassLoader classLoader = instance.getClass().getClassLoader(); 353 URL url = classLoader.getResource("/"); 354 if (url == null) { 355 servletClassesPath = "."; 357 } else { 358 servletClassesPath = url.getPath(); 359 } 360 } 361 log.debug("servletClassesPath = " + servletClassesPath); 362 if (servletClassesPath.endsWith(File.separator) == false) { 363 servletClassesPath = servletClassesPath + File.separatorChar; 364 } 366 } 367 return servletClassesPath; 368 } 369 370 380 public static void createTextFile(InputStream inputStream, String textFile) 381 throws IOException { 382 383 if (inputStream == null) { 384 throw new IllegalArgumentException ("Does not accept null input"); 385 } 386 OutputStream outputStream = null; 387 try { 388 byte[] srcByte = FileUtil.getBytes(inputStream); 389 outputStream = new FileOutputStream(textFile); 390 outputStream.write(srcByte); 391 return; 392 } catch (IOException e) { 393 log.error("Error", e); 394 throw e; 395 } finally { inputStream.close(); 397 if (outputStream != null) outputStream.close(); 398 } 399 } 400 401 410 public static void writeFile(String content, String fileName, String destEncoding) 411 throws FileNotFoundException, IOException { 412 413 File file = null; 414 try { 415 file = new File(fileName); 416 if (file.isFile() == false) { 417 throw new IOException("'" + fileName + "' is not a file."); 418 } 419 if (file.canWrite() == false) { 420 throw new IOException("'" + fileName + "' is a read-only file."); 421 } 422 } finally { 423 } 425 426 BufferedWriter out = null; 427 try { 428 FileOutputStream fos = new FileOutputStream(fileName); 429 out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding)); 430 431 out.write(content); 432 out.flush(); 433 } catch (FileNotFoundException fe) { 434 log.error("Error", fe); 435 throw fe; 436 } catch (IOException e) { 437 log.error("Error", e); 438 throw e; 439 } finally { 440 try { 441 if (out != null) out.close(); 442 } catch (IOException ex) {} 443 } 444 } 445 446 public static String readFile(String fileName, String srcEncoding) 447 throws FileNotFoundException, IOException { 448 449 File file = null; 450 try { 451 file = new File(fileName); 452 if (file.isFile() == false) { 453 throw new IOException("'" + fileName + "' is not a file."); 454 } 455 } finally { 456 } 458 459 BufferedReader reader = null; 460 try { 461 StringBuffer result = new StringBuffer (1024); 462 FileInputStream fis = new FileInputStream(fileName); 463 reader = new BufferedReader(new InputStreamReader(fis, srcEncoding)); 464 465 char[] block = new char[512]; 466 while (true) { 467 int readLength = reader.read(block); 468 if (readLength == -1) break; result.append(block, 0, readLength); 470 } 471 return result.toString(); 472 } catch (FileNotFoundException fe) { 473 log.error("Error", fe); 474 throw fe; 475 } catch (IOException e) { 476 log.error("Error", e); 477 throw e; 478 } finally { 479 try { 480 if (reader != null) reader.close(); 481 } catch (IOException ex) {} 482 } 483 } 484 485 490 public static String [] getLastLines(File file, int linesToReturn) 491 throws IOException, FileNotFoundException { 492 493 final int AVERAGE_CHARS_PER_LINE = 250; 494 final int BYTES_PER_CHAR = 2; 495 496 RandomAccessFile randomAccessFile = null; 497 StringBuffer buffer = new StringBuffer (linesToReturn * AVERAGE_CHARS_PER_LINE); 498 int lineTotal = 0; 499 try { 500 randomAccessFile = new RandomAccessFile(file, "r"); 501 long byteTotal = randomAccessFile.length(); 502 long byteEstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE * BYTES_PER_CHAR; 503 504 long offset = byteTotal - byteEstimateToRead; 505 if (offset < 0) { 506 offset = 0; 507 } 508 509 randomAccessFile.seek(offset); 510 512 String line = null; 513 String lineUTF8 = null; 514 while ((line = randomAccessFile.readLine()) != null) { 515 lineUTF8 = new String (line.getBytes("ISO8859_1"), "UTF-8"); 516 lineTotal++; 517 buffer.append(lineUTF8).append("\n"); 518 } 519 } finally { 520 if (randomAccessFile != null) { 521 try { 522 randomAccessFile.close(); 523 } catch (IOException ex) { 524 } 525 } 526 } 527 528 String [] resultLines = new String [linesToReturn]; 529 BufferedReader in = null; 530 try { 531 in = new BufferedReader(new StringReader(buffer.toString())); 532 533 int start = lineTotal - linesToReturn; if (start < 0) start = 0; for (int i = 0; i < start; i++) { 536 in.readLine(); } 538 539 int i = 0; 540 String line = null; 541 while ((line = in.readLine()) != null) { 542 resultLines[i] = line; 543 i++; 544 } 545 } catch (IOException ie) { 546 log.error("Error" + ie); 547 throw ie; 548 } finally { 549 if (in != null) { 550 try { 551 in.close(); 552 } catch (IOException ex) { 553 } 554 } 555 } 556 return resultLines; 557 } 558 559 public static String getHumanSize(long size) { 560 561 int sizeToStringLength = String.valueOf(size).length(); 562 String humanSize = ""; 563 DecimalFormat formatter = new DecimalFormat ("##0.##"); 564 if (sizeToStringLength > 9) { 565 humanSize += formatter.format((double) size / (1024 * 1024 * 1024)) + " GB"; 566 } else if (sizeToStringLength > 6) { 567 humanSize += formatter.format((double) size / (1024 * 1024)) + " MB"; 568 } else if (sizeToStringLength > 3) { 569 humanSize += formatter.format((double) size / 1024) + " KB"; 570 } else { 571 humanSize += String.valueOf(size) + " Bytes"; 572 } 573 return humanSize; 574 } 575 } 576 | Popular Tags |