1 19 package org.netbeans.lib.cvsclient.file; 20 21 import java.io.*; 22 23 29 public class FileUtils { 30 private static FileReadOnlyHandler fileReadOnlyHandler; 31 32 35 public static FileReadOnlyHandler getFileReadOnlyHandler() { 36 return fileReadOnlyHandler; 37 } 38 39 42 public static void setFileReadOnlyHandler(FileReadOnlyHandler fileReadOnlyHandler) { 43 FileUtils.fileReadOnlyHandler = fileReadOnlyHandler; 44 } 45 46 52 public static void setFileReadOnly(File file, boolean readOnly) throws IOException { 53 if (getFileReadOnlyHandler() == null) { 54 return; 55 } 56 57 getFileReadOnlyHandler().setFileReadOnly(file, readOnly); 58 } 59 60 63 public static void copyFile(File sourceFile, File targetFile) throws IOException { 64 if (sourceFile == null || targetFile == null) { 65 throw new NullPointerException ("sourceFile and targetFile must not be null"); } 67 68 File directory = targetFile.getParentFile(); 70 if (!directory.exists() && !directory.mkdirs()) { 71 throw new IOException("Could not create directory '" + directory + "'"); } 73 74 InputStream inputStream = null; 75 OutputStream outputStream = null; 76 try { 77 inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); 78 outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); 79 80 try { 81 byte[] buffer = new byte[32768]; 82 for (int readBytes = inputStream.read(buffer); 83 readBytes > 0; 84 readBytes = inputStream.read(buffer)) { 85 outputStream.write(buffer, 0, readBytes); 86 } 87 } 88 catch (IOException ex) { 89 targetFile.delete(); 90 throw ex; 91 } 92 } 93 finally { 94 if (inputStream != null) { 95 try { 96 inputStream.close(); 97 } 98 catch (IOException ex) { 99 } 101 } 102 if (outputStream != null) { 103 try { 104 outputStream.close(); 105 } 106 catch (IOException ex) { 107 } 109 } 110 } 111 } 112 113 114 119 public static void renameFile(File orig, File dest) throws IOException { 120 boolean destExists = dest.exists(); 121 if (destExists) { 122 for (int i = 0; i<3; i++) { 123 if (dest.delete()) { 124 destExists = false; 125 break; 126 } 127 try { 128 Thread.sleep(71); 129 } catch (InterruptedException e) { 130 } 131 } 132 } 133 134 if (destExists == false) { 135 for (int i = 0; i<3; i++) { 136 if (orig.renameTo(dest)) { 137 return; 138 } 139 try { 140 Thread.sleep(71); 141 } catch (InterruptedException e) { 142 } 143 } 144 } 145 146 FileUtils.copyFile(orig, dest); 148 149 for (int i = 0; i<3; i++) { 150 if (orig.delete()) { 151 return; 152 } 153 try { 154 Thread.sleep(71); 155 } catch (InterruptedException e) { 156 } 157 } 158 throw new IOException("Can not delete: " + orig.getAbsolutePath()); } 160 161 164 private FileUtils() { 165 } 166 } 167 | Popular Tags |