org.apache.common.io-FileUtils详解

时间:2023-12-29 14:15:56

org.apache.common.io---FileUtils详解
getTempDirectoryPath():返回临时目录路径;

 public static String getTempDirectoryPath() {
return System.getProperty("java.io.tmpdir");
}

getTempDirectory():返回临时目录文件路径的File实例;

public static File getTempDirectory() {
return new File(getTempDirectoryPath());
}

getUserDirectoryPath():返回用户目录路径;

public static String getUserDirectoryPath() {
return System.getProperty("user.home");
}

getUserDirectory():返回用户目录路径的File实例

public static File getUserDirectory() {
return new File(getUserDirectoryPath());
}

openInputStream(File file):通过指定文件创建一个输入流;如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。

public static FileOutputStream openOutputStream(File file) throws IOException {
return openOutputStream(file, false);
}
public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canWrite() == false) {
throw new IOException("File '" + file + "' cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null) {
if (!parent.mkdirs() && !parent.isDirectory()) {
throw new IOException("Directory '" + parent + "' could not be created");
}
}
}
return new FileOutputStream(file, append);
}

byteCountToDisplaySize(long size):返回指定数值的计算机表示(KB,MB,GB);

/**
* The number of bytes in a kilobyte.
*/
public static final long ONE_KB = 1024; /**
* The number of bytes in a megabyte.
*/
public static final long ONE_MB = ONE_KB * ONE_KB;
/**
* The number of bytes in a gigabyte.
*/
public static final long ONE_GB = ONE_KB * ONE_MB;
public static String byteCountToDisplaySize(long size) {
String displaySize; // if (size / ONE_EB > 0) {
// displaySize = String.valueOf(size / ONE_EB) + " EB";
// } else if (size / ONE_PB > 0) {
// displaySize = String.valueOf(size / ONE_PB) + " PB";
// } else if (size / ONE_TB > 0) {
// displaySize = String.valueOf(size / ONE_TB) + " TB";
// } else
if (size / ONE_GB > 0) {
displaySize = String.valueOf(size / ONE_GB) + " GB";
} else if (size / ONE_MB > 0) {
displaySize = String.valueOf(size / ONE_MB) + " MB";
} else if (size / ONE_KB > 0) {
displaySize = String.valueOf(size / ONE_KB) + " KB";
} else {
displaySize = String.valueOf(size) + " bytes";
}
return displaySize;
}

touch(File file):更新指定文件最终修改时间和访问时间;若文件不存在则生成空文件;Closeable 是可以关闭的数据源或目标。调用 close 方法可释放对象保存的资源(如打开文件)。

public static void touch(File file) throws IOException {
if (!file.exists()) {
OutputStream out = openOutputStream(file);
IOUtils.closeQuietly(out);
}
boolean success = file.setLastModified(System.currentTimeMillis());
if (!success) {
throw new IOException("Unable to set the last modification time for " + file);
}
}
public static void closeQuietly(OutputStream output) {
closeQuietly((Closeable)output);
}
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ioe) {
// ignore
}
}

convertFileCollectionToFileArray(Collection<File> files):把文件集合转换为数组形式;

public static File[] convertFileCollectionToFileArray(Collection<File> files) {
return files.toArray(new File[files.size()]);
}

contentEquals(File file1, File file2):比较两个文件内容是否相同;两个文件都不存在表示相同;不能比较目录,会抛出异常;

public static boolean contentEquals(File file1, File file2) throws IOException {
boolean file1Exists = file1.exists();
if (file1Exists != file2.exists()) {
return false;
} if (!file1Exists) {
// two not existing files are equal
return true;
} if (file1.isDirectory() || file2.isDirectory()) {
// don't want to compare directory contents
throw new IOException("Can't compare directories, only files");
} if (file1.length() != file2.length()) {
// lengths differ, cannot be equal
return false;
} if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
// same file
return true;
} InputStream input1 = null;
InputStream input2 = null;
try {
input1 = new FileInputStream(file1);
input2 = new FileInputStream(file2);
return IOUtils.contentEquals(input1, input2); } finally {
IOUtils.closeQuietly(input1);
IOUtils.closeQuietly(input2);
}
}

copyFileToDirectory(File srcFile, File
destDir),copyFileToDirectory(File srcFile, File destDir, boolean
preserveFileDate):拷贝源文件到指定目录;如果目标目录不存在,则会被创建;如果目标文件存在,源文件会把它覆盖;如果第三个参数为
true,设置拷贝的目标文件最终修改时间与源文件时间一样;

public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {
copyFileToDirectory(srcFile, destDir, true);
}

copyFile(File input, OutputStream output):把一个文件写到输出流里;返回写入的字节数大小;

public static long copyFile(File input, OutputStream output) throws IOException {
final FileInputStream fis = new FileInputStream(input);
try {
return IOUtils.copyLarge(fis, output);
} finally {
fis.close();
}
}

copyDirectory(File srcDir, File destDir),copyDirectory(File srcDir, File destDir,
            boolean preserveFileDate),copyDirectory(File srcDir, File destDir,
            FileFilter filter, boolean preserveFileDate):拷贝源目录及目录下所有文件到指定目录,第三个参数如果为true,设置拷贝后的目录最后修改时间与源目录时间相同
filter为过滤后的文件进行拷贝;

public static void copyDirectory(File srcDir, File destDir) throws IOException {
copyDirectory(srcDir, destDir, true);
}

copyInputStreamToFile(InputStream source, File destination):把输入流中的内容写到指定文件中;

deleteDirectory(File directory):删除指定目录文件及目录下所有内容;

cleanDirectory(File directory):清空指定目录文件下所有内容,但不删除目录;

boolean deleteQuietly(File file):删除指定目录文件及目录下所有内容;但不抛出异常,异常在内部已经捕获;

readFileToString(File file, String encoding),readFileToString(File file):读取指定文件内容到一个字符串;第二个参数为指定的字符集编码;

readFileToByteArray(File file):读取指定文件到字节数组;

readLines(File file, String encoding):读取指定文件按行存入字符串List,第二个参数为指定的字符集编码;

writeStringToFile(File
file, String data, String encoding),writeStringToFile(File file, String
data, String encoding, boolean
append):按指定的编码把字符串写入指定文件中;第四个参数如果为true,则把内容写到文件最后;如果文件不存在则创建;

writeByteArrayToFile(File file, byte[] data),writeByteArrayToFile(File file, byte[] data, boolean append):同上;

forceDelete(File file):删除指定文件,如果为目录,则清空目录并删除目录文件,如果为文件,直接删除文件;

forceDeleteOnExit(File file):在JVM退出时进行删除,如果为目录,则清空目录并删除目录文件,如果为文件,直接删除文件;

cleanDirectoryOnExit(File directory) :在JVM退出时清空目录;

forceMkdir(File directory):创建指定目录,如果失败抛出异常;

sizeOf(File file):返回指定文件大小或者目录下所有文件大小之和;

isFileNewer(File file, File reference):判断给定文件与比较文件哪个更新(创建时间更晚),第二个参数为参照文件;

isFileOlder(File file, File reference):判断给定文件与比较文件哪个更旧(创建时间更早),第二个参数为参照文件;

moveDirectory(File srcDir, File destDir):将源目录移动为指定目录;重命名那句代码,如果生命名成功就无须再移动文件了,如果生命名失败再进行拷贝和删除操作;

public static void moveDirectory(File srcDir, File destDir) throws IOException {
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (!srcDir.exists()) {
throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
}
if (!srcDir.isDirectory()) {
throw new IOException("Source '" + srcDir + "' is not a directory");
}
if (destDir.exists()) {
throw new FileExistsException("Destination '" + destDir + "' already exists");
}
boolean rename = srcDir.renameTo(destDir);
if (!rename) {
copyDirectory( srcDir, destDir );
deleteDirectory( srcDir );
if (srcDir.exists()) {
throw new IOException("Failed to delete original directory '" + srcDir +
"' after copy to '" + destDir + "'");
}
}
}

moveDirectoryToDirectory(File src, File destDir, boolean createDestDir):把源目录移动到指定目录下,如果目标目录不存在,根据第三个参数是否创建;如果不存在并且不创建,则会抛出异常;

moveFile(File srcFile, File destFile):移动文件,同上;

moveFileToDirectory(File srcFile, File destDir, boolean createDestDir):移动文件到指定目录;如果目标目录不存在,根据第三个参数是否创建;如果不存在并且不创建,则会抛出异常;