1 33 34 package edu.rice.cs.util; 35 36 import java.io.*; 37 import java.net.MalformedURLException ; 38 import java.net.URL ; 39 import java.util.*; 40 41 import edu.rice.cs.drjava.config.FileOption; 42 43 import edu.rice.cs.util.Log; 44 45 51 public abstract class FileOps { 52 53 private static Log _log = new Log("FileOpsTest.txt", false); 54 55 56 57 public static final File NONEXISTENT_FILE = new File("") { 58 public String getAbsolutePath() { return ""; } 59 public String getName() { return ""; } 60 public String toString() { return ""; } 61 public boolean exists() { return false; } 62 }; 63 64 69 @Deprecated public static File makeFile(String path) { 70 File f = new File(path); 71 try { return f.getCanonicalFile(); } 72 catch(IOException e) { return f; } 73 } 74 75 80 @Deprecated public static File makeFile(File parentDir, String child) { 81 File f = new File(parentDir, child); 82 try { return f.getCanonicalFile(); } 83 catch(IOException e) { return f; } 84 } 85 86 92 @Deprecated public static boolean inFileTree(File f, File root) { 93 if (root == null || f == null) return false; 94 try { 95 if (! f.isDirectory()) f = f.getParentFile(); 96 String filePath = f.getCanonicalPath() + File.separator; 97 String projectPath = root.getCanonicalPath() + File.separator; 98 return (filePath.startsWith(projectPath)); 99 } 100 catch(IOException e) { return false; } 101 } 102 103 104 121 public static File makeRelativeTo(File f, File b) throws IOException, SecurityException { 122 File base = b.getCanonicalFile(); 123 File abs = f.getCanonicalFile(); if (! base.isDirectory()) base = base.getParentFile(); 125 126 String last = ""; 127 if (! abs.isDirectory()) { 128 String tmp = abs.getPath(); 129 last = tmp.substring(tmp.lastIndexOf(File.separator) + 1); 130 abs = abs.getParentFile(); 131 } 132 133 String [] basParts = splitFile(base); 135 String [] absParts = splitFile(abs); 136 137 final StringBuilder result = new StringBuilder (); 138 int diffIndex = -1; 141 boolean different = false; 142 for (int i = 0; i < basParts.length; i++) { 143 if (!different && ((i >= absParts.length) || !basParts[i].equals(absParts[i]))) { 144 different = true; 145 diffIndex = i; 146 } 147 if (different) result.append("..").append(File.separator); 148 } 149 if (diffIndex < 0) diffIndex = basParts.length; 150 for (int i = diffIndex; i < absParts.length; i++) { 151 result.append(absParts[i]).append(File.separator); 152 } 153 result.append(last); 154 return new File(result.toString()); 156 } 157 158 165 @Deprecated public static String [] splitFile(File fileToSplit) { 166 String path = fileToSplit.getPath(); 167 ArrayList<String > list = new ArrayList<String >(); 168 while (! path.equals("")) { 169 int idx = path.indexOf(File.separator); 170 if (idx < 0) { 171 list.add(path); 172 path = ""; 173 } 174 else { 175 list.add(path.substring(0,idx)); 176 path = path.substring(idx + 1); 177 } 178 } 179 return list.toArray(new String [list.size()]); 180 } 181 182 192 @Deprecated public static ArrayList<File> getFilesInDir(File d, boolean recur, FileFilter f) { 193 ArrayList<File> l = new ArrayList<File>(); 194 getFilesInDir(d, l, recur, f); 195 return l; 196 } 197 198 201 private static void getFilesInDir(File d, List<File> acc, boolean recur, FileFilter filter) { 202 if (d.isDirectory()) { 203 File[] files = d.listFiles(filter); 204 if (files != null) { for (File f: files) { 206 if (f.isDirectory() && recur) getFilesInDir(f, acc, recur, filter); 207 else if (f.isFile()) acc.add(f); 208 } 209 } 210 } 211 } 212 213 219 @Deprecated public static File getCanonicalFile(File f) { 220 if (f == null) return f; 221 try { return f.getCanonicalFile(); } 222 catch (IOException e) { } 223 catch (SecurityException e) { } 224 return f.getAbsoluteFile(); 225 } 226 227 232 @Deprecated public static String getCanonicalPath(File f) { return getCanonicalFile(f).getPath(); } 233 234 235 public static File validate(File f) { 236 if (f.exists()) return f; 237 return FileOption.NULL_FILE; } 239 240 246 @Deprecated public static final FileFilter JAVA_FILE_FILTER = new FileFilter() { 247 public boolean accept(File f){ 248 final StringBuilder name = new StringBuilder (f.getAbsolutePath()); 252 String shortName = f.getName(); 253 if (shortName.length() < 6) return false; 254 name.delete(name.length() - 5, name.length()); 255 name.append(".java"); 256 File test = new File(name.toString()); 257 return (test.equals(f)); 258 } 259 public String getDescription() { return "Java Source Files (*.java)"; } 260 }; 261 262 269 @Deprecated public static byte[] readStreamAsBytes(final InputStream stream) throws IOException { 270 BufferedInputStream buffered; 271 272 if (stream instanceof BufferedInputStream) buffered = (BufferedInputStream) stream; 273 else buffered = new BufferedInputStream(stream); 274 275 ByteArrayOutputStream out = new ByteArrayOutputStream(); 276 277 int readVal = buffered.read(); 278 while (readVal != -1) { 279 out.write(readVal); 280 readVal = buffered.read(); 281 } 282 283 stream.close(); 284 return out.toByteArray(); 285 } 286 287 290 @Deprecated public static String readFileAsString(final File file) throws IOException { 291 FileReader reader = new FileReader(file); 292 final StringBuilder buf = new StringBuilder (); 293 294 while (reader.ready()) { 295 char c = (char) reader.read(); 296 buf.append(c); 297 } 298 299 reader.close(); 300 return buf.toString(); 301 } 302 303 309 @Deprecated public static void copyFile(File source, File dest) throws IOException { 310 String text = readFileAsString(source); 311 writeStringToFile(dest, text); 312 } 313 314 322 @Deprecated public static File writeStringToNewTempFile(final String prefix, final String suffix, final String text) 323 throws IOException { 324 325 File file = File.createTempFile(prefix, suffix); 326 file.deleteOnExit(); 327 writeStringToFile(file, text); 328 return file; 329 } 330 331 336 @Deprecated public static void writeStringToFile(File file, String text) throws IOException { 337 writeStringToFile(file, text, false); 338 } 339 340 346 @Deprecated public static void writeStringToFile(File file, String text, boolean append) throws IOException { 347 FileWriter writer = new FileWriter(file, append); 348 writer.write(text); 349 writer.close(); 350 } 351 352 360 @Deprecated public static boolean writeIfPossible(File file, String text, boolean append) { 361 try { 362 writeStringToFile(file, text, append); 363 return true; 364 } 365 catch(IOException e) { return false; } 366 } 367 368 375 @Deprecated public static File createTempDirectory(final String name) throws IOException { 376 return createTempDirectory(name, null); 377 } 378 379 389 @Deprecated public static File createTempDirectory(final String name, final File parent) throws IOException { 390 File file = File.createTempFile(name, "", parent); 391 file.delete(); 392 file.mkdir(); 393 file.deleteOnExit(); 394 395 return file; 396 } 397 398 405 @Deprecated public static boolean deleteDirectory(final File dir) { 406 if (! dir.isDirectory()) { 408 boolean res; 409 res = dir.delete(); 410 return res; 412 } 413 414 boolean ret = true; 415 File[] childFiles = dir.listFiles(); 416 if (childFiles!=null) { for (File f: childFiles) { ret = ret && deleteDirectory(f); } 418 } 419 420 ret = ret && dir.delete(); 422 return ret; 424 } 425 426 431 @Deprecated public static void deleteDirectoryOnExit(final File dir) { 432 433 _log.log("Deleting file/directory " + dir + " on exit"); 435 dir.deleteOnExit(); 436 437 if (dir.isDirectory()) { 440 File[] childFiles = dir.listFiles(); 441 if (childFiles != null) { for (File f: childFiles) { deleteDirectoryOnExit(f); } 443 } 444 } 445 } 446 447 452 public static LinkedList<String > packageExplore(String prefix, File root) { 453 454 class PrefixAndFile { 455 public String prefix; 456 public File root; 457 public PrefixAndFile(String prefix, File root) { 458 this.root = root; 459 this.prefix = prefix; 460 } 461 } 462 463 final Set<File> exploredDirectories = new HashSet<File>(); 466 467 LinkedList<String > output = new LinkedList<String >(); 468 Stack<PrefixAndFile> working = new Stack<PrefixAndFile>(); 469 working.push(new PrefixAndFile(prefix, root)); 470 exploredDirectories.add(root); 471 472 FileFilter directoryFilter = new FileFilter(){ 474 public boolean accept(File f){ 475 boolean toReturn = f.isDirectory() && ! exploredDirectories.contains(f); 476 exploredDirectories.add(f); 477 return toReturn; 478 } 479 public String getDescription() { return "All Folders"; } 480 }; 481 482 while (! working.empty()) { 485 PrefixAndFile current = working.pop(); 486 File [] subDirectories = current.root.listFiles(directoryFilter); 487 if (subDirectories!=null) { for (File dir: subDirectories) { 489 PrefixAndFile paf; 490 if (current.prefix.equals("")) paf = new PrefixAndFile(dir.getName(), dir); 492 else paf = new PrefixAndFile(current.prefix + "." + dir.getName(), dir); 493 working.push(paf); 494 } 495 } 496 File [] javaFiles = current.root.listFiles(JAVA_FILE_FILTER); 497 498 if (javaFiles!=null) { if (javaFiles.length != 0 && !current.prefix.equals("")) { 501 output.add(current.prefix); 502 } 504 } 505 } 506 return output; 507 } 508 509 516 @Deprecated public static boolean renameFile(File file, File dest) { 517 if (dest.exists()) dest.delete(); 518 return file.renameTo(dest); 519 } 520 521 534 public static void saveFile(FileSaver fileSaver) throws IOException { 535 536 boolean makeBackup = fileSaver.shouldBackup(); 539 boolean success = false; 540 File file = fileSaver.getTargetFile(); 541 File backup = null; 542 boolean tempFileUsed = true; 543 if (file.exists() && !file.canWrite()) throw new IOException("Permission denied"); 547 548 if (makeBackup) { 549 backup = fileSaver.getBackupFile(); 550 if (!renameFile(file, backup)){ 551 throw new IOException("Save failed. Could not create backup file " 552 + backup.getAbsolutePath() + 553 "\nIt may be possible to save by disabling file backups\n"); 554 } 555 fileSaver.backupDone(); 556 } 557 558 561 File parent = file.getParentFile(); 565 File tempFile = File.createTempFile("drjava", ".temp", parent); 566 567 570 try { 571 574 FileOutputStream fos; 575 try { 576 581 fos = new FileOutputStream(tempFile); 582 } 583 catch (FileNotFoundException fnfe) { 584 if (fileSaver.continueWhenTempFileCreationFails()) { 585 fos = new FileOutputStream(file); 586 tempFileUsed = false; 587 } 588 else throw new IOException("Could not create temp file " + tempFile + " in attempt to save " + file); 589 } 590 BufferedOutputStream bos = new BufferedOutputStream(fos); 591 fileSaver.saveTo(bos); 592 bos.close(); 593 fos.close(); 594 595 if (tempFileUsed && !renameFile(tempFile, file)) 596 throw new IOException("Save failed. Another process may be using " + file + "."); 597 598 success = true; 599 } 600 finally { 601 604 if (tempFileUsed) tempFile.delete(); 605 606 if (makeBackup) { 607 609 if (success) fileSaver.backupDone(); 610 else renameFile(backup, file); 611 } 612 } 613 } 614 615 public interface FileSaver { 616 617 620 public abstract File getBackupFile() throws IOException; 621 622 625 public abstract boolean shouldBackup() throws IOException; 626 627 631 public abstract boolean continueWhenTempFileCreationFails(); 632 633 634 public abstract void backupDone(); 635 636 643 public abstract void saveTo(OutputStream os) throws IOException; 644 645 650 public abstract File getTargetFile() throws IOException; 651 } 652 653 657 public abstract static class DefaultFileSaver implements FileSaver { 658 659 private File outputFile = null; 660 private static Set<File> filesNotNeedingBackup = new HashSet<File>(); 661 private static boolean backupsEnabled = true; 662 663 664 private boolean isCanonical = false; 665 666 667 public static void setBackupsEnabled(boolean isEnabled) { backupsEnabled = isEnabled; } 668 669 public DefaultFileSaver(File file){ outputFile = file.getAbsoluteFile(); } 670 671 public boolean continueWhenTempFileCreationFails(){ return true; } 672 673 public File getBackupFile() throws IOException{ return new File(getTargetFile().getPath() + "~"); } 674 675 public boolean shouldBackup() throws IOException{ 676 if (!backupsEnabled) return false; 677 if (!getTargetFile().exists()) return false; 678 if (filesNotNeedingBackup.contains(getTargetFile())) return false; 679 return true; 680 } 681 682 public void backupDone() { 683 try { filesNotNeedingBackup.add(getTargetFile()); } 684 catch (IOException ioe) { throw new UnexpectedException(ioe, "getTargetFile should fail earlier"); } 685 } 686 687 public File getTargetFile() throws IOException{ 688 if (!isCanonical) { 689 outputFile = outputFile.getCanonicalFile(); 690 isCanonical = true; 691 } 692 return outputFile; 693 } 694 } 695 696 709 @Deprecated public static String convertToAbsolutePathEntries(String path) { 710 String pathSep = System.getProperty("path.separator"); 711 712 path += pathSep + "x"; 716 717 719 String [] pathEntries = path.split(pathSep); 723 final StringBuilder sb = new StringBuilder (); 724 for(int i = 0; i<pathEntries.length - 1; ++i) { File f = new File(pathEntries[i]); 726 sb.append(f.getAbsolutePath()); 727 sb.append(pathSep); 728 } 729 String reconstructedPath = sb.toString(); 730 731 if (reconstructedPath.length()!=0) { 734 reconstructedPath = reconstructedPath.substring(0, reconstructedPath.length() - 1); 735 } 736 737 return reconstructedPath; 738 } 739 740 745 public static File getValidDirectory(File file) { 746 if ((file==FileOption.NULL_FILE)||(file==null)) { 748 file = new File(System.getProperty("user.home")); 749 } 750 while (!file.exists()) { 751 file = file.getParentFile(); 753 } 754 if (file==null) { 755 file = new File(System.getProperty("user.home")); 757 } 758 if (!file.isDirectory()) { 760 if (file.getParent() != null) file = file.getParentFile(); 761 } 762 763 if (file.exists() && file.isDirectory()) { 765 return file; 766 } 767 768 throw new UnexpectedException(new IOException("File's parent file is null")); 771 } 772 773 780 public static URL toURL(File f) throws MalformedURLException { return f.toURL(); } 781 } 782 | Popular Tags |