1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
|
package compbio.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
/**
* Utility methods to work with file system
*
* @author pvtroshin
* @version 1.0 July 2009
*/
public class FileUtil {
private static final Logger log = Logger.getLogger(FileUtil.class);
public static boolean isDirectoryEmpty(String dirpath) {
assert !Util.isEmpty(dirpath);
return isDirectoryEmpty(new File(dirpath));
}
public static boolean exist(String file) {
assert !Util.isEmpty(file);
return new File(file).exists();
}
/**
* Copy the content of the sourceFile to the destination File.
*
* @param sourceFile
* the source
* @param destinationFile
* the destination
* @throws IOException
*/
public static void copy(File sourceFile, File destinationFile)
throws IOException {
if (!destinationFile.exists()) {
destinationFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destinationFile).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
} finally {
if (destination != null && destination.isOpen()) {
destination.close();
}
if (source != null && source.isOpen()) {
source.close();
}
}
}
/**
*
* Method copies the content of the source Stream to the destination File.
* The source stream are left open.
*
* @param source
* the source
* @param destination
* the destination
* @throws IOException
*/
public static void copy(InputStream source, File destination)
throws IOException {
BufferedInputStream bfinput = new BufferedInputStream(source);
BufferedOutputStream destStream = null;
try {
destStream = new BufferedOutputStream(new FileOutputStream(
destination));
byte[] buff = new byte[1024];
int length = 0;
while (true) {
length = bfinput.read(buff);
if (length <= 0) {
break;
}
destStream.write(buff, 0, length);
}
destStream.close();
} finally {
closeSilently(destStream);
}
}
private static boolean isNotEmpty(String filepath,
int minSizeExpectedInBytes) {
assert !Util.isEmpty(filepath);
File file = new File(filepath);
if (!file.exists()) {
return false;
}
assert file.isFile() : "File expected! but directory is given!";
assert file.canRead() : "Does not have permissions to read the file!";
long bytelenght = file.length();
// Assume that file must have content
if (bytelenght > minSizeExpectedInBytes) {
return true;
} else {
return false;
}
}
public static boolean hasData(String filepath, int minSizeExpectedInBytes) {
return isNotEmpty(filepath, minSizeExpectedInBytes);
}
public static boolean hasData(String filepath) {
return isNotEmpty(filepath, 0);
}
public static boolean isDirectoryEmpty(File directory) {
assert directory != null;
assert directory.canRead() : "Cannot read!";
assert directory.isDirectory() : "Directory expected, but file is given!";
return directory.listFiles().length == 0;
}
/**
* Get list of all files from the particular directory
*
* @param directory
* name
* @return Array of the files in the directory
*/
public static File[] getAllFiles(final String directory) {
final File ff = new File(directory);
return ff.listFiles();
}
/**
* Get list of files from the particular directory passed through FileFilter
*
* @param directory
* name
* @param fileFilter
* @return Array of the files in the directory which satisfy the FileFilter
* criteria
*/
public static File[] getFiles(final String directory,
final FileFilter fileFilter) {
final File ff = new File(directory);
return ff.listFiles(fileFilter);
}
/**
*
* @param fileName
* @return file extension
*/
public static String getFileExtension(final String fileName) {
return fileName.substring(fileName.lastIndexOf(".")).trim();
}
/**
* Create a temp file of a given size Util.getTempFile
*
* @param sizeinKBytes
* value must be between 1 (kb) and 1000000 (1Gb)
* @return File
* @throws IOException
*/
public static File getTempFile(final int sizeinKBytes) throws IOException {
assert sizeinKBytes > 0 : "Size must be positive integer but the value received is: "
+ sizeinKBytes;
assert sizeinKBytes < 1000000 : "Size must be less than 1 Gb!";
final File file = File.createTempFile("" + System.currentTimeMillis(),
".bin");
final OutputStream out = new FileOutputStream(file);
final byte buf[] = new byte[1024];
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) i;
}
for (int i = 0; i < sizeinKBytes; i++) {
out.write(buf);
}
try {
out.close();
} finally {
closeSilently(log, out);
}
return file;
}
public static byte[] readFile(final File file) throws IOException {
FileInputStream inStream = new FileInputStream(file);
final BufferedInputStream bis = new BufferedInputStream(inStream);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final byte[] buffer = new byte[256];
int length;
while (true) {
length = bis.read(buffer);
if (0 >= length) {
break;
}
out.write(buffer, 0, length);
}
byte[] result = out.toByteArray();
try {
out.close();
bis.close();
inStream.close();
} finally {
closeSilently(log, out);
closeSilently(log, bis);
closeSilently(log, inStream);
}
return result;
}
public static String readFileToString(final InputStream inStream)
throws IOException {
final byte[] bytes = new byte[inStream.available()];
inStream.read(bytes);
final ByteArrayOutputStream contentStr = new ByteArrayOutputStream();
contentStr.write(bytes);
String content = contentStr.toString();
try {
contentStr.close();
} finally {
closeSilently(log, contentStr);
}
return content;
}
/**
* FilenameFilter implementation Allow filter the directory contents by file
* extension.
*/
public static class ExtensionFilter implements FilenameFilter {
String extension = "";
public ExtensionFilter(final String extension) {
this.extension = extension;
}
public boolean accept(final File dir, final String name) {
return (name.endsWith(this.extension));
}
}
/**
* Reads file into a single String, returns empty string if file was empty
*
* @param file
* @return
* @throws IOException
*/
public static String readFileToString(final File file) throws IOException {
String fileStr = "";
String line = null;
if (file.exists()) {
FileReader reader = new FileReader(file);
final BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
fileStr += line + "\n";
}
try {
br.close();
reader.close();
} finally {
closeSilently(log, br);
closeSilently(log, reader);
}
}
return fileStr;
}
/**
* Write any String data to file.
*
* @param data
* @param filePathandName
* File name with full path
* @throws IOException
*/
public static void writeToFile(final String data,
final String filePathandName) throws IOException {
FileWriter fwriter = null;
BufferedWriter bw = null;
try {
fwriter = new FileWriter(filePathandName);
bw = new BufferedWriter(fwriter);
bw.write(data);
bw.close();
fwriter.close();
} finally {
closeSilently(log, bw);
closeSilently(log, fwriter);
}
}
/**
* Write any String data to file.
*
* @param data
* @param filePathandName
* File name with full path
* @throws IOException
*/
public static void writeToFile(final byte[] data,
final String filePathandName, boolean append) throws IOException {
FileOutputStream outStream = null;
BufferedOutputStream bw = null;
try {
outStream = new FileOutputStream(filePathandName, append);
bw = new BufferedOutputStream(outStream);
bw.write(data);
bw.close();
outStream.close();
} finally {
closeSilently(log, bw);
closeSilently(log, outStream);
}
}
public static void appendToFile(final byte[] data,
final String filePathandName) throws IOException {
writeToFile(data, filePathandName, true);
}
public static void writeToFile(final byte[] data,
final String filePathandName) throws IOException {
writeToFile(data, filePathandName, false);
}
public static List<String> getFileNameList(String path) {
return getFileNameList(path, null);
}
public static List<String> getFileNameList(String path,
FilenameFilter filter) {
assert !compbio.util.Util.isEmpty(path);
assert new File(path).isDirectory();
if (filter == null) {
return Arrays.asList(new File(path).list());
}
return Arrays.asList(new File(path).list(filter));
}
public final static void closeSilently(Logger log, Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e.getCause());
}
}
}
public final static void closeSilently(java.util.logging.Logger log,
Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
log.severe(e.getLocalizedMessage() + " Cause: " + e.getCause());
}
}
}
public final static void closeSilently(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e.getCause());
}
}
}
}
|