1 16 package org.apache.commons.io.output; 17 18 import java.io.File ; 19 import java.io.FileWriter ; 20 import java.io.IOException ; 21 import java.io.Writer ; 22 23 36 public class LockableFileWriter extends Writer { 37 38 private static final String LCK = ".lck"; 39 40 private File lockFile = null; 41 42 private FileWriter writer = null; 43 44 private boolean append = false; 45 46 51 public LockableFileWriter(String fileName) 52 throws IOException { 53 this(fileName, false, null); 54 } 55 56 62 public LockableFileWriter(String fileName, boolean append) 63 throws IOException { 64 this(fileName, append, null); 65 } 66 67 74 public LockableFileWriter(String fileName, boolean append, String lockDir) 75 throws IOException { 76 this(new File (fileName), append, lockDir); 77 } 78 79 84 public LockableFileWriter(File file) 85 throws IOException { 86 this(file, false, null); 87 } 88 89 95 public LockableFileWriter(File file, boolean append) 96 throws IOException { 97 this(file, append, null); 98 } 99 100 107 public LockableFileWriter(File file, boolean append, String lockDir) 108 throws IOException { 109 this.append = append; 110 111 if (lockDir == null) { 112 lockDir = System.getProperty("java.io.tmpdir"); 113 } 114 testLockDir(new File (lockDir)); 115 this.lockFile = new File (lockDir, file.getName() + LCK); 116 createLock(); 117 118 this.writer = new FileWriter (file.getAbsolutePath(), this.append); 119 } 120 121 private void testLockDir(File lockDir) 122 throws IOException { 123 if (!lockDir.exists()) { 124 throw new IOException ( 125 "Could not find lockDir: " + lockDir.getAbsolutePath()); 126 } 127 if (!lockDir.canWrite()) { 128 throw new IOException ( 129 "Could not write to lockDir: " + lockDir.getAbsolutePath()); 130 } 131 } 132 133 private void createLock() 134 throws IOException { 135 synchronized (LockableFileWriter.class) { 136 if (!lockFile.createNewFile()) { 137 throw new IOException ("Can't write file, lock " + 138 lockFile.getAbsolutePath() + " exists"); 139 } 140 lockFile.deleteOnExit(); 141 } 142 } 143 144 145 public void close() 146 throws IOException { 147 try { 148 writer.close(); 149 } finally { 150 lockFile.delete(); 151 } 152 } 153 154 155 public void write(char[] cbuf, int off, int len) 156 throws IOException { 157 writer.write(cbuf, off, len); 158 } 159 160 161 public void flush() 162 throws IOException { 163 writer.flush(); 164 } 165 } 166 | Popular Tags |