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 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
| package com.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class Util {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
// Constructors -------------------------------------------------------------------------------
private Util() {
// Utility class, hide constructor.
}
// Writers ------------------------------------------------------------------------------------
/**
* Write byte array to file. If file already exists, it will be overwritten.
* @param file The file where the given byte array have to be written to.
* @param bytes The byte array which have to be written to the given file.
* @throws IOException If writing file fails.
*/
public static void write(File file, byte[] bytes) throws IOException {
write(file, new ByteArrayInputStream(bytes), false);
}
/**
* Write byte array to file with option to append to file or not. If not, then any existing
* file will be overwritten.
* @param file The file where the given byte array have to be written to.
* @param bytes The byte array which have to be written to the given file.
* @param append Append to file?
* @throws IOException If writing file fails.
*/
public static void write(File file, byte[] bytes, boolean append) throws IOException {
write(file, new ByteArrayInputStream(bytes), append);
}
/**
* Write byte inputstream to file. If file already exists, it will be overwritten.It's highly
* recommended to feed the inputstream as BufferedInputStream or ByteArrayInputStream as those
* are been automatically buffered.
* @param file The file where the given byte inputstream have to be written to.
* @param input The byte inputstream which have to be written to the given file.
* @throws IOException If writing file fails.
*/
public static void write(File file, InputStream input) throws IOException {
write(file, input, false);
}
/**
* Write byte inputstream to file with option to append to file or not. If not, then any
* existing file will be overwritten. It's highly recommended to feed the inputstream as
* BufferedInputStream or ByteArrayInputStream as those are been automatically buffered.
* @param file The file where the given byte inputstream have to be written to.
* @param input The byte inputstream which have to be written to the given file.
* @param append Append to file?
* @throws IOException If writing file fails.
*/
public static void write(File file, InputStream input, boolean append) throws IOException {
mkdirs(file);
BufferedOutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(file, append));
int data = -1;
while ((data = input.read()) != -1) {
output.write(data);
}
} finally {
close(input, file);
close(output, file);
}
}
/**
* Write character array to file. If file already exists, it will be overwritten.
* @param file The file where the given character array have to be written to.
* @param chars The character array which have to be written to the given file.
* @throws IOException If writing file fails.
*/
public static void write(File file, char[] chars) throws IOException {
write(file, new CharArrayReader(chars), false);
}
/**
* Write character array to file with option to append to file or not. If not, then any
* existing file will be overwritten.
* @param file The file where the given character array have to be written to.
* @param chars The character array which have to be written to the given file.
* @param append Append to file?
* @throws IOException If writing file fails.
*/
public static void write(File file, char[] chars, boolean append) throws IOException {
write(file, new CharArrayReader(chars), append);
}
/**
* Write string value to file. If file already exists, it will be overwritten.
* @param file The file where the given string value have to be written to.
* @param string The string value which have to be written to the given file.
* @throws IOException If writing file fails.
*/
public static void write(File file, String string) throws IOException {
write(file, new CharArrayReader(string.toCharArray()), false);
}
/**
* Write string value to file with option to append to file or not. If not, then any existing
* file will be overwritten.
* @param file The file where the given string value have to be written to.
* @param string The string value which have to be written to the given file.
* @param append Append to file?
* @throws IOException If writing file fails.
*/
public static void write(File file, String string, boolean append) throws IOException {
write(file, new CharArrayReader(string.toCharArray()), append);
}
/**
* Write character reader to file. If file already exists, it will be overwritten. It's highly
* recommended to feed the reader as BufferedReader or CharArrayReader as those are been
* automatically buffered.
* @param file The file where the given character reader have to be written to.
* @param reader The character reader which have to be written to the given file.
* @throws IOException If writing file fails.
*/
public static void write(File file, Reader reader) throws IOException {
write(file, reader, false);
}
/**
* Write character reader to file with option to append to file or not. If not, then any
* existing file will be overwritten. It's highly recommended to feed the reader as
* BufferedReader or CharArrayReader as those are been automatically buffered.
* @param file The file where the given character reader have to be written to.
* @param reader The character reader which have to be written to the given file.
* @param append Append to file?
* @throws IOException If writing file fails.
*/
public static void write(File file, Reader reader, boolean append) throws IOException {
mkdirs(file);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file, append));
int data = -1;
while ((data = reader.read()) != -1) {
writer.write(data);
}
} finally {
close(reader, file);
close(writer, file);
}
}
/**
* Write list of String records to file. If file already exists, it will be overwritten.
* @param file The file where the given character reader have to be written to.
* @param records The list of String records which have to be written to the given file.
* @throws IOException If writing file fails.
*/
public static void write(File file, List<String> records) throws IOException {
write(file, records, false);
}
/**
* Write list of String records to file with option to append to file or not. If not, then any
* existing file will be overwritten.
* @param file The file where the given character reader have to be written to.
* @param records The list of String records which have to be written to the given file.
* @param append Append to file?
* @throws IOException If writing file fails.
*/
public static void write(File file, List<String> records, boolean append) throws IOException {
mkdirs(file);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file, append));
for (String record : records) {
writer.write(record);
writer.write(LINE_SEPARATOR);
}
} finally {
close(writer, file);
}
}
// Readers ------------------------------------------------------------------------------------
/**
* Read byte array from file. Take care with big files, this would be memory hogging, rather
* use readStream() instead.
* @param file The file to read the byte array from.
* @return The byte array with the file contents.
* @throws IOException If reading file fails.
*/
public static byte[] readBytes(File file) throws IOException {
BufferedInputStream stream = (BufferedInputStream) readStream(file);
byte[] bytes = new byte[stream.available()];
stream.read(bytes);
return bytes;
}
/**
* Read byte stream from file.
* @param file The file to read the byte stream from.
* @return The byte stream with the file contents (actually: BufferedInputStream).
* @throws IOException If reading file fails.
*/
public static InputStream readStream(File file) throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}
/**
* Read character array from file. Take care with big files, this would be memory hogging,
* rather use readReader() instead.
* @param file The file to read the character array from.
* @return The character array with the file contents.
* @throws IOException If reading file fails.
*/
public static char[] readChars(File file) throws IOException {
BufferedReader reader = (BufferedReader) readReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
return chars;
}
/**
* Read string value from file. Take care with big files, this would be memory hogging, rather
* use readReader() instead.
* @param file The file to read the string value from.
* @return The string value with the file contents.
* @throws IOException If reading file fails.
*/
public static String readString(File file) throws IOException {
return new String(readChars(file));
}
/**
* Read character reader from file.
* @param file The file to read the character reader from.
* @return The character reader with the file contents (actually: BufferedReader).
* @throws IOException If reading file fails.
*/
public static Reader readReader(File file) throws IOException {
return new BufferedReader(new FileReader(file));
}
/**
* Read list of String records from file.
* @param file The file to read the character writer from.
* @return A list of String records which represents lines of the file contents.
* @throws IOException If reading file fails.
*/
public static List<String> readRecords(File file) throws IOException {
BufferedReader reader = (BufferedReader) readReader(file);
List<String> records = new ArrayList<String>();
String record = null;
try {
while ((record = reader.readLine()) != null) {
records.add(record);
}
} finally {
close(reader, file);
}
return records;
}
// Copiers ------------------------------------------------------------------------------------
/**
* Copy file. Any existing file at the destination will be overwritten.
* @param source The file to read the contents from.
* @param destination The file to write the contents to.
* @throws IOException If copying file fails.
*/
public static void copy(File source, File destination) throws IOException {
copy(source, destination, true);
}
/**
* Copy file with the option to overwrite any existing file at the destination.
* @param source The file to read the contents from.
* @param destination The file to write the contents to.
* @param overwrite Set whether to overwrite any existing file at the destination.
* @throws IOException If the destination file already exists while <tt>overwrite</tt> is set
* to false, or if copying file fails.
*/
public static void copy(File source, File destination, boolean overwrite) throws IOException {
if (destination.exists() && !overwrite) {
throw new IOException(
"Copying file " + source.getPath() + " to " + destination.getPath() + " failed."
+ " The destination file already exists.");
}
mkdirs(destination);
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(source));
output = new BufferedOutputStream(new FileOutputStream(destination));
int data = -1;
while ((data = input.read()) != -1) {
output.write(data);
}
} finally {
close(input, source);
close(output, destination);
}
}
// Movers -------------------------------------------------------------------------------------
/**
* Move (rename) file. Any existing file at the destination will be overwritten.
* @param source The file to be moved.
* @param destination The new destination of the file.
* @throws IOException If moving file fails.
*/
public static void move(File source, File destination) throws IOException {
move(source, destination, true);
}
/**
* Move (rename) file with the option to overwrite any existing file at the destination.
* @param source The file to be moved.
* @param destination The new destination of the file.
* @param overwrite Set whether to overwrite any existing file at the destination.
* @throws IOException If the destination file already exists while <tt>overwrite</tt> is set
* to false, or if moving file fails.
*/
public static void move(File source, File destination, boolean overwrite) throws IOException {
if (destination.exists()) {
if (overwrite) {
destination.delete();
} else {
throw new IOException(
"Moving file " + source.getPath() + " to " + destination.getPath() + " failed."
+ " The destination file already exists.");
}
}
mkdirs(destination);
if (!source.renameTo(destination)) {
throw new IOException(
"Moving file " + source.getPath() + " to " + destination.getPath() + " failed.");
}
}
// Filenames ----------------------------------------------------------------------------------
/**
* Trim the eventual file path from the given file name. Anything before the last occurred "/"
* and "\" will be trimmed, including the slash.
* @param fileName The file name to trim the file path from.
* @return The file name with the file path trimmed.
*/
public static String trimFilePath(String fileName) {
return fileName
.substring(fileName.lastIndexOf("/") + 1)
.substring(fileName.lastIndexOf("\\") + 1);
}
/**
* Generate unique file based on the given path and name. If the file exists, then it will
* add "[i]" to the file name as long as the file exists. The value of i can be between
* 0 and 2147483647 (the value of Integer.MAX_VALUE).
* @param filePath The path of the unique file.
* @param fileName The name of the unique file.
* @return The unique file.
* @throws IOException If unique file cannot be generated, this can be caused if all file
* names are already in use. You may consider another filename instead.
*/
public static File uniqueFile(File filePath, String fileName) throws IOException {
File file = new File(filePath, fileName);
if (file.exists()) {
// Split filename and add braces, e.g. "name.ext" --> "name[", "].ext".
String prefix;
String suffix;
int dotIndex = fileName.lastIndexOf(".");
if (dotIndex > -1) {
prefix = fileName.substring(0, dotIndex) + "[";
suffix = "]" + fileName.substring(dotIndex);
} else {
prefix = fileName + "[";
suffix = "]";
}
int count = 0;
// Add counter to filename as long as file exists.
while (file.exists()) {
if (count < 0) { // int++ restarts at -2147483648 after 2147483647.
throw new IOException("No unique filename available for " + fileName
+ " in path " + filePath.getPath() + ".");
}
// Glue counter between prefix and suffix, e.g. "name[" + count + "].ext".
file = new File(filePath, prefix + (count++) + suffix);
}
}
return file;
}
// Helpers ------------------------------------------------------------------------------------
/**
* Check and create missing parent directories for the given file.
* @param file The file to check and create the missing parent directories for.
* @throws IOException If the given file is actually not a file or if creating parent
* directories fails.
*/
private static void mkdirs(File file) throws IOException {
if (file.exists() && !file.isFile()) {
throw new IOException("File " + file.getPath() + " is actually not a file.");
}
File parentFile = file.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
throw new IOException("Creating directories " + parentFile.getPath() + " failed.");
}
}
/**
* Close the given I/O resource of the given file.
* @param resource The I/O resource to be closed.
* @param file The I/O resource's subject.
*/
private static void close(Closeable resource, File file) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
String message = "Closing file " + file.getPath() + " failed.";
// Do your thing with the exception and the message. Print it, log it or mail it.
System.err.println(message);
e.printStackTrace();
}
}
}
} |
Partager