本文主要是介绍FileUtils方法大全(1),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
FileUtils
获取系统的临时目录路径:getTempDirectoryPath()
publicstatic String getTempDirectoryPath() {
returnSystem.getProperty("java.io.tmpdir");
}
获取代表系统临时目录的文件:getTempDirectory ()
publicstatic File getTempDirectory() {
return newFile(getTempDirectoryPath());
}
获取用户的主目录路径:getUserDirectoryPath()
publicstatic String getUserDirectoryPath() {
returnSystem.getProperty("user.home");
}
获取代表用户主目录的文件:getUserDirectory()
publicstatic File getUserDirectory() {
return newFile(getUserDirectoryPath());
}
根据指定的文件获取一个新的文件输入流:openInputStream(File file)
publicstatic FileInputStream openInputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw newIOException("File '" + file + "' exists but is adirectory");
}
if (file.canRead() == false) {
throw newIOException("File '" + file + "' cannot be read");
}
} else {
throw newFileNotFoundException("File '" + file + "' does notexist");
}
return new FileInputStream(file);
}
根据指定的文件获取一个新的文件输出流:openOutputStream (File file)
publicstatic FileOutputStream openOutputStream(File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File'" + file + "' exists but is a directory");
}
if (file.canWrite() == false) {
throw newIOException("File '" + file + "' cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null &&parent.exists() == false) {
if (parent.mkdirs() ==false) {
throw newIOException("File '" + file + "' could not be created");
}
}
}
return new FileOutputStream(file);
}
字节转换成直观带单位的值(包括单位GB,MB,KB或字节)byteCountToDisplaySize(long size)
public static StringbyteCountToDisplaySize(long size) {
String displaySize;
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)
public static void touch(File file) throwsIOException {
if (!file.exists()) {
OutputStream out =openOutputStream(file);
IOUtils.closeQuietly(out);
}
boolean success =file.setLastModified(System.currentTimeMillis());
if (!success) {
throw new IOException("Unableto set the last modification time for " + file);
}
}
把相应的文件集合转换成文件数组convertFileCollectionToFileArray(Collection<File> files)
publicstatic File[] convertFileCollectionToFileArray(Collection<File> files) {
return files.toArray(newFile[files.size()]);
}
根据一个过滤规则获取一个目录下的文件innerListFiles(Collection<File> files, File directory,IOFileFilterfilter)
privatestatic void innerListFiles(Collection<File> files, File directory,
IOFileFilter filter) {
File[] found =directory.listFiles((FileFilter) filter);
if (found != null) {
for (File file : found) {
if (file.isDirectory()) {
innerListFiles(files,file, filter);
} else {
files.add(file);
}
}
}
}
根据一个IOFileFilter过滤规则获取一个目录下的文件集合listFiles(
File directory, IOFileFilterfileFilter, IOFileFilter dirFilter)
publicstatic Collection<File> listFiles(
File directory, IOFileFilterfileFilter, IOFileFilter dirFilter) {
if (!directory.isDirectory()) {
throw newIllegalArgumentException(
"Parameter'directory' is not a directory");
}
if (fileFilter == null) {
throw newNullPointerException("Parameter 'fileFilter' is null");
}
//Setup effective file filter
IOFileFilter effFileFilter =FileFilterUtils.and(fileFilter,
FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));
//Setup effective directory filter
IOFileFilter effDirFilter;
if (dirFilter == null) {
effDirFilter =FalseFileFilter.INSTANCE;
} else {
effDirFilter =FileFilterUtils.and(dirFilter,
DirectoryFileFilter.INSTANCE);
}
//Find files
Collection<File> files = newjava.util.LinkedList<File>();
innerListFiles(files, directory,
FileFilterUtils.or(effFileFilter, effDirFilter));
return files;
}
根据一个IOFileFilter过滤规则获取一个目录下的文件集合的Iterator迭代器iterateFiles(
File directory, IOFileFilterfileFilter, IOFileFilter dirFilter)
public static Iterator<File>iterateFiles(
File directory, IOFileFilterfileFilter, IOFileFilter dirFilter) {
return listFiles(directory,fileFilter, dirFilter).iterator();
}
把指定的字符串数组变成后缀名格式字符串数组toSuffixes(String[] extensions)
privatestatic String[] toSuffixes(String[] extensions) {
String[] suffixes = newString[extensions.length];
for (int i = 0; i <extensions.length; i++) {
suffixes[i] = "." +extensions[i];
}
return suffixes;
}
查找一个目录下面符合对应扩展名的文件的集合listFiles(
File directory, String[]extensions, boolean recursive)
public static Collection<File>listFiles(
File directory, String[]extensions, boolean recursive) {
IOFileFilter filter;
if (extensions == null) {
filter =TrueFileFilter.INSTANCE;
} else {
String[] suffixes =toSuffixes(extensions);
filter = newSuffixFileFilter(suffixes);
}
return listFiles(directory, filter,
(recursive ?TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE));
}
查找一个目录下面符合对应扩展名的文件的集合的迭代器Iterator<File> iterateFiles(
File directory, String[]extensions, boolean recursive)
publicstatic Iterator<File> iterateFiles(
File directory, String[]extensions, boolean recursive) {
return listFiles(directory,extensions, recursive).iterator();
}
判断两个文件是否相等contentEquals(Filefile1, File file2)
publicstatic boolean contentEquals(File file1, File file2) throws IOException {
boolean file1Exists =file1.exists();
if (file1Exists != file2.exists()) {
return false;
}
if (!file1Exists) {
// two not existing files areequal
return true;
}
if (file1.isDirectory() ||file2.isDirectory()) {
// don't want to comparedirectory contents
throw newIOException("Can't compare directories, only files");
}
if (file1.length() !=file2.length()) {
// lengths differ, cannot beequal
return false;
}
if(file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
// same file
return true;
}
InputStream input1 = null;
InputStream input2 = null;
try {
input1 = newFileInputStream(file1);
input2 = newFileInputStream(file2);
returnIOUtils.contentEquals(input1, input2);
} finally {
IOUtils.closeQuietly(input1);
IOUtils.closeQuietly(input2);
}
}
根据一个Url来创建一个文件toFile(URL url)
publicstatic File toFile(URL url) {
if (url == null ||!"file".equalsIgnoreCase(url.getProtocol())) {
return null;
} else {
String filename =url.getFile().replace('/', File.separatorChar);
filename = decodeUrl(filename);
return new File(filename);
}
}
对一个Url字符串进行将指定的URL按照RFC 3986进行转换decodeUrl(Stringurl)
staticString decodeUrl(String url) {
String decoded = url;
if (url != null &&url.indexOf('%') >= 0) {
int n = url.length();
StringBuffer buffer = newStringBuffer();
ByteBuffer bytes =ByteBuffer.allocate(n);
for (int i = 0; i < n;) {
if (url.charAt(i) == '%') {
try {
do {
byte octet =(byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);
bytes.put(octet);
i += 3;
} while (i < n&& url.charAt(i) == '%');
continue;
} catch(RuntimeException e) {
// malformedpercent-encoded octet, fall through and
// append charactersliterally
} finally {
if (bytes.position()> 0) {
bytes.flip();
buffer.append(UTF8.decode(bytes).toString());
bytes.clear();
}
}
}
buffer.append(url.charAt(i++));
}
decoded = buffer.toString();
}
return decoded;
}
将一个URL数组转化成一个文件数组toFiles(URL[] urls)
publicstatic File[] toFiles(URL[] urls) {
if (urls == null || urls.length ==0) {
return EMPTY_FILE_ARRAY;
}
File[] files = newFile[urls.length];
for (int i = 0; i < urls.length;i++) {
URL url = urls[i];
if (url != null) {
if(url.getProtocol().equals("file") == false) {
throw newIllegalArgumentException(
"URL couldnot be converted to a File: " + url);
}
files[i] = toFile(url);
}
}
return files;
}
将一个文件数组转化成一个URL数组toURLs(File[] files)
public static URL[] toURLs(File[] files)throws IOException {
URL[] urls = new URL[files.length];
for (int i = 0; i < urls.length;i++) {
urls[i] =files[i].toURI().toURL();
}
return urls;
}
拷贝一个文件到指定的目录文件copyFileToDirectory(File srcFile, File destDir)
publicstatic void copyFileToDirectory(File srcFile, File destDir) throws IOException{
copyFileToDirectory(srcFile,destDir, true);
}
拷贝一个文件到指定的目录文件并且设置是否更新文件的最近修改时间copyFileToDirectory(File srcFile, File destDir, booleanpreserveFileDate)
publicstatic void copyFileToDirectory(File srcFile, File destDir, booleanpreserveFileDate) throws IOException {
if (destDir == null) {
throw newNullPointerException("Destination must not be null");
}
if (destDir.exists() &&destDir.isDirectory() == false) {
throw newIllegalArgumentException("Destination '" + destDir + "' is not adirectory");
}
File destFile = new File(destDir,srcFile.getName());
copyFile(srcFile, destFile,preserveFileDate);
}
拷贝文件到新的文件中并且保存最近修改时间copyFile(File srcFile, File destFile)
publicstatic void copyFile(File srcFile, File destFile) throws IOException {
copyFile(srcFile, destFile, true);
}
拷贝文件到新的文件中并且设置是否保存最近修改时间copyFile(File srcFile, File destFile,
boolean preserveFileDate)
publicstatic void copyFile(File srcFile, File destFile,
boolean preserveFileDate) throwsIOException {
if (srcFile == null) {
throw newNullPointerException("Source must not be null");
}
if (destFile == null) {
throw newNullPointerException("Destination must not be null");
}
if (srcFile.exists() == false) {
throw newFileNotFoundException("Source '" + srcFile + "' does notexist");
}
if (srcFile.isDirectory()) {
throw newIOException("Source '" + srcFile + "' exists but is adirectory");
}
if(srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
throw newIOException("Source '" + srcFile + "' and destination '" +destFile + "' are the same");
}
if (destFile.getParentFile() != null&& destFile.getParentFile().exists() == false) {
if(destFile.getParentFile().mkdirs() == false) {
throw newIOException("Destination '" + destFile + "' directory cannot becreated");
}
}
if (destFile.exists() &&destFile.canWrite() == false) {
throw newIOException("Destination '" + destFile + "' exists but isread-only");
}
doCopyFile(srcFile, destFile,preserveFileDate);
}
拷贝文件到新的文件中并且设置是否保存最近修改时间doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
private static void doCopyFile(File srcFile,File destFile, boolean preserveFileDate) throws IOException {
if (destFile.exists() &&destFile.isDirectory()) {
throw newIOException("Destination '" + destFile + "' exists but is adirectory");
}
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel input = null;
FileChannel output = null;
try {
fis = newFileInputStream(srcFile);
fos = newFileOutputStream(destFile);
input = fis.getChannel();
output = fos.getChannel();
long size = input.size();
long pos = 0;
long count = 0;
while (pos < size) {
count = (size - pos) >FIFTY_MB ? FIFTY_MB : (size - pos);
pos +=output.transferFrom(input, pos, count);
}
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(fis);
}
if (srcFile.length() !=destFile.length()) {
throw newIOException("Failed to copy full contents from '" +
srcFile + "' to '"+ destFile + "'");
}
if (preserveFileDate) {
destFile.setLastModified(srcFile.lastModified());
}
}
将一个目录拷贝到另一目录中,并且保存最近更新时间copyDirectoryToDirectory(File srcDir, File destDir)
publicstatic void copyDirectoryToDirectory(File srcDir, File destDir) throwsIOException {
if (srcDir == null) {
throw newNullPointerException("Source must not be null");
}
if (srcDir.exists() &&srcDir.isDirectory() == false) {
throw new IllegalArgumentException("Source'" + destDir + "' is not a directory");
}
if (destDir == null) {
throw newNullPointerException("Destination must not be null");
}
if (destDir.exists() &&destDir.isDirectory() == false) {
throw newIllegalArgumentException("Destination '" + destDir + "' is not adirectory");
}
copyDirectory(srcDir, newFile(destDir, srcDir.getName()), true);
}
拷贝整个目录到新的位置,并且保存最近修改时间copyDirectory(File srcDir, File destDir)
publicstatic void copyDirectory(File srcDir, File destDir) throws IOException{
copyDirectory(srcDir, destDir,true);
}
拷贝整个目录到新的位置,并且设置是否保存最近修改时间copyDirectory(File srcDir, File destDir, boolean preserveFileDate)
publicstatic void copyDirectory(File srcDir, File destDir,
boolean preserveFileDate) throwsIOException {
copyDirectory(srcDir, destDir, null,preserveFileDate);
}
拷贝过滤后的目录到指定的位置,并且保存最近修改时间copyDirectory(File srcDir, File destDir, FileFilter filter)
publicstatic void copyDirectory(File srcDir, File destDir,
FileFilter filter) throwsIOException {
copyDirectory(srcDir, destDir,filter, true);
}
拷贝过滤后的目录到指定的位置,并且设置是否保存最近修改时间copyDirectory(File srcDir, File destDir,FileFilter filter, booleanpreserveFileDate)
publicstatic void copyDirectory(File srcDir, File destDir,
FileFilter filter, booleanpreserveFileDate) throws IOException {
if (srcDir == null) {
throw newNullPointerException("Source must not be null");
}
if (destDir == null) {
throw newNullPointerException("Destination must not be null");
}
if (srcDir.exists() == false) {
throw newFileNotFoundException("Source '" + srcDir + "' does notexist");
}
if (srcDir.isDirectory() == false){
throw newIOException("Source '" + srcDir + "' exists but is not adirectory");
}
if(srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
throw newIOException("Source '" + srcDir + "' and destination '" +destDir + "' are the same");
}
// Cater for destination being directorywithin the source directory (see IO-141)
List<String> exclusionList =null;
if(destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
File[] srcFiles = filter ==null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles != null &&srcFiles.length > 0) {
exclusionList = newArrayList<String>(srcFiles.length);
for (File srcFile :srcFiles) {
File copiedFile = newFile(destDir, srcFile.getName());
exclusionList.add(copiedFile.getCanonicalPath());
}
}
}
doCopyDirectory(srcDir, destDir,filter, preserveFileDate, exclusionList);
}
内部拷贝目录的方法doCopyDirectory(FilesrcDir, File destDir, FileFilter filter,
boolean preserveFileDate,List<String> exclusionList)
privatestatic void doCopyDirectory(File srcDir, File destDir, FileFilter filter,
boolean preserveFileDate,List<String> exclusionList) throws IOException {
// recurse
File[] files = filter == null ?srcDir.listFiles() : srcDir.listFiles(filter);
if (files == null) { // null if security restricted
throw newIOException("Failed to list contents of " + srcDir);
}
if (destDir.exists()) {
if (destDir.isDirectory() ==false) {
throw newIOException("Destination '" + destDir + "' exists but is not adirectory");
}
} else {
if (destDir.mkdirs() == false){
throw newIOException("Destination '" + destDir + "' directory cannot becreated");
}
}
if (destDir.canWrite() == false) {
throw newIOException("Destination '" + destDir + "' cannot be writtento");
}
for (File file : files) {
File copiedFile = newFile(destDir, file.getName());
if (exclusionList == null ||!exclusionList.contains(file.getCanonicalPath())) {
if (file.isDirectory()) {
doCopyDirectory(file,copiedFile, filter, preserveFileDate, exclusionList);
} else {
doCopyFile(file,copiedFile, preserveFileDate);
}
}
}
// Do this last, as the above hasprobably affected directory metadata
if (preserveFileDate) {
destDir.setLastModified(srcDir.lastModified());
}
}
根据一个Url拷贝字节到一个文件中copyURLToFile(URL source, File destination)
publicstatic void copyURLToFile(URL source, File destination) throws IOException {
InputStream input =source.openStream();
copyInputStreamToFile(input,destination);
}
根据一个Url拷贝字节到一个文件中,并且可以设置连接的超时时间和读取的超时时间
copyURLToFile(URLsource, File destination,
int connectionTimeout, int readTimeout)
publicstatic void copyURLToFile(URL source, File destination,
int connectionTimeout, int readTimeout)throws IOException {
URLConnection connection =source.openConnection();
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(readTimeout);
InputStream input =connection.getInputStream();
copyInputStreamToFile(input,destination);
}
拷贝一个字节流到一个文件中,如果这个文件不存在则新创建一个,存在的话将被重写进内容copyInputStreamToFile(InputStream source, File destination)
public static voidcopyInputStreamToFile(InputStream source, File destination) throws IOException{
try {
FileOutputStream output =openOutputStream(destination);
try {
IOUtils.copy(source,output);
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(source);
}
}
递归的删除一个目录deleteDirectory(Filedirectory)
publicstatic void deleteDirectory(File directory) throws IOException {
if (!directory.exists()) {
return;
}
if (!isSymlink(directory)) {
cleanDirectory(directory);
}
if (!directory.delete()) {
String message =
"Unable to deletedirectory " + directory + ".";
throw new IOException(message);
}
}
这篇关于FileUtils方法大全(1)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!