一、前言
关于camel-core源码包中org.apache.camel.util.FileUtil文件操作工具类,主要对路径通用处理normalizePath、创建临时文件createTempFile、创建临时目录路径createNewTempDir、删除指定目录removeDir、删除指定文件delete、复制文件copyFile、创建文件createNewFile、是否具体路径判断isAbsolute扥。
二、源码说明
package org.apache.camel.util;@b@@b@import java.io.File;@b@import java.io.IOException;@b@import java.nio.file.CopyOption;@b@import java.nio.file.Files;@b@import java.nio.file.StandardCopyOption;@b@import java.util.ArrayDeque;@b@import java.util.Deque;@b@import java.util.Iterator;@b@import java.util.Locale;@b@import java.util.Random;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@@b@public final class FileUtil@b@{@b@ public static final int BUFFER_SIZE = 131072;@b@ private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class);@b@ private static final int RETRY_SLEEP_MILLIS = 10;@b@ private static final String USER_DIR_KEY = "user.dir";@b@ private static final File USER_DIR = new File(System.getProperty("user.dir"));@b@ private static File defaultTempDir;@b@ private static Thread shutdownHook;@b@ private static boolean windowsOs = initWindowsOs();@b@@b@ private static boolean initWindowsOs()@b@ {@b@ String osName = System.getProperty("os.name").toLowerCase(Locale.ENGLISH);@b@ return osName.contains("windows");@b@ }@b@@b@ public static File getUserDir() {@b@ return USER_DIR;@b@ }@b@@b@ public static String normalizePath(String path)@b@ {@b@ if (path == null) {@b@ return null;@b@ }@b@@b@ if (isWindows())@b@ {@b@ return path.replace('/', '\\');@b@ }@b@@b@ return path.replace('\\', '/');@b@ }@b@@b@ public static boolean isWindows()@b@ {@b@ return windowsOs;@b@ }@b@@b@ @Deprecated@b@ public static File createTempFile(String prefix, String suffix) throws IOException {@b@ return createTempFile(prefix, suffix, null);@b@ }@b@@b@ public static File createTempFile(String prefix, String suffix, File parentDir) throws IOException@b@ {@b@ File parent = (parentDir == null) ? getDefaultTempDir() : parentDir;@b@@b@ if (suffix == null)@b@ suffix = ".tmp";@b@@b@ if (prefix == null)@b@ prefix = "camel";@b@ else if (prefix.length() < 3) {@b@ prefix = prefix + "camel";@b@ }@b@@b@ parent.mkdirs();@b@@b@ return File.createTempFile(prefix, suffix, parent);@b@ }@b@@b@ public static String stripLeadingSeparator(String name)@b@ {@b@ if (name == null)@b@ return null;@b@@b@ while ((name.startsWith("/")) || (name.startsWith(File.separator)))@b@ name = name.substring(1);@b@@b@ return name;@b@ }@b@@b@ public static boolean hasLeadingSeparator(String name)@b@ {@b@ if (name == null) {@b@ return false;@b@ }@b@@b@ return ((name.startsWith("/")) || (name.startsWith(File.separator)));@b@ }@b@@b@ public static String stripFirstLeadingSeparator(String name)@b@ {@b@ if (name == null)@b@ return null;@b@@b@ if ((name.startsWith("/")) || (name.startsWith(File.separator)))@b@ name = name.substring(1);@b@@b@ return name;@b@ }@b@@b@ public static String stripTrailingSeparator(String name)@b@ {@b@ if (ObjectHelper.isEmpty(name)) {@b@ return name;@b@ }@b@@b@ String s = name;@b@@b@ while ((s.endsWith("/")) || (s.endsWith(File.separator))) {@b@ s = s.substring(0, s.length() - 1);@b@ }@b@@b@ if (ObjectHelper.isEmpty(s)) {@b@ return name;@b@ }@b@@b@ return s;@b@ }@b@@b@ public static String stripPath(String name)@b@ {@b@ if (name == null)@b@ return null;@b@@b@ int posUnix = name.lastIndexOf(47);@b@ int posWin = name.lastIndexOf(92);@b@ int pos = Math.max(posUnix, posWin);@b@@b@ if (pos != -1)@b@ return name.substring(pos + 1);@b@@b@ return name;@b@ }@b@@b@ public static String stripExt(String name) {@b@ return stripExt(name, false);@b@ }@b@@b@ public static String stripExt(String name, boolean singleMode) {@b@ if (name == null) {@b@ return null;@b@ }@b@@b@ int posUnix = name.lastIndexOf(47);@b@ int posWin = name.lastIndexOf(92);@b@ int pos = Math.max(posUnix, posWin);@b@@b@ if (pos > 0) {@b@ String onlyName = name.substring(pos + 1);@b@ int pos2 = (singleMode) ? onlyName.lastIndexOf(46) : onlyName.indexOf(46);@b@ if (pos2 > 0)@b@ return name.substring(0, pos + pos2 + 1);@b@ }@b@ else@b@ {@b@ int pos2 = (singleMode) ? name.lastIndexOf(46) : name.indexOf(46);@b@ if (pos2 > 0)@b@ return name.substring(0, pos2);@b@@b@ }@b@@b@ return name;@b@ }@b@@b@ public static String onlyExt(String name) {@b@ return onlyExt(name, false);@b@ }@b@@b@ public static String onlyExt(String name, boolean singleMode) {@b@ if (name == null)@b@ return null;@b@@b@ name = stripPath(name);@b@@b@ int pos = (singleMode) ? name.lastIndexOf(46) : name.indexOf(46);@b@ if (pos != -1)@b@ return name.substring(pos + 1);@b@@b@ return null;@b@ }@b@@b@ public static String onlyPath(String name)@b@ {@b@ if (name == null) {@b@ return null;@b@ }@b@@b@ int posUnix = name.lastIndexOf(47);@b@ int posWin = name.lastIndexOf(92);@b@ int pos = Math.max(posUnix, posWin);@b@@b@ if (pos > 0)@b@ return name.substring(0, pos);@b@ if (pos == 0)@b@ {@b@ return name.substring(0, 1);@b@ }@b@@b@ return null;@b@ }@b@@b@ public static String compactPath(String path)@b@ {@b@ return compactPath(path, "" + File.separatorChar);@b@ }@b@@b@ public static String compactPath(String path, char separator)@b@ {@b@ return compactPath(path, "" + separator);@b@ }@b@@b@ public static String compactPath(String path, String separator)@b@ {@b@ if (path == null) {@b@ return null;@b@ }@b@@b@ if ((path.indexOf(47) == -1) && (path.indexOf(92) == -1)) {@b@ return path;@b@ }@b@@b@ path = normalizePath(path);@b@@b@ boolean endsWithSlash = (path.endsWith("/")) || (path.endsWith("\\"));@b@@b@ boolean startsWithSlash = (path.startsWith("/")) || (path.startsWith("\\"));@b@@b@ Deque stack = new ArrayDeque();@b@@b@ String separatorRegex = "\\\\|/";@b@ String[] parts = path.split(separatorRegex);@b@ String[] arrayOfString1 = parts; int i = arrayOfString1.length; for (int j = 0; j < i; ++j) { String part = arrayOfString1[j];@b@ if ((part.equals("..")) && (!(stack.isEmpty())) && (!("..".equals(stack.peek()))))@b@ {@b@ stack.pop();@b@ } else if (!(part.equals("."))) { if (part.isEmpty()) { break label204:@b@ }@b@@b@ stack.push(part);@b@ }@b@@b@ }@b@@b@ label204: StringBuilder sb = new StringBuilder();@b@@b@ if (startsWithSlash) {@b@ sb.append(separator);@b@ }@b@@b@ Iterator it = stack.descendingIterator();@b@ while (true) { do { if (!(it.hasNext())) break label285;@b@ sb.append((String)it.next()); }@b@ while (!(it.hasNext()));@b@ sb.append(separator);@b@ }@b@@b@ if ((endsWithSlash) && (stack.size() > 0)) {@b@ label285: sb.append(separator);@b@ }@b@@b@ return sb.toString();@b@ }@b@@b@ @Deprecated@b@ private static synchronized File getDefaultTempDir() {@b@ if ((defaultTempDir != null) && (defaultTempDir.exists())) {@b@ return defaultTempDir;@b@ }@b@@b@ defaultTempDir = createNewTempDir();@b@@b@ shutdownHook = new Thread()@b@ {@b@ public void run() {@b@ FileUtil.removeDir(FileUtil.access$000());@b@ }@b@@b@ };@b@ Runtime.getRuntime().addShutdownHook(shutdownHook);@b@@b@ return defaultTempDir;@b@ }@b@@b@ @Deprecated@b@ private static File createNewTempDir()@b@ {@b@ String s = System.getProperty("java.io.tmpdir");@b@ File checkExists = new File(s);@b@ if (!(checkExists.exists()))@b@ {@b@ throw new RuntimeException("The directory " + checkExists@b@ .getAbsolutePath() + " does not exist, please set java.io.tempdir to an existing directory");@b@ }@b@@b@ if (!(checkExists.canWrite()))@b@ {@b@ throw new RuntimeException("The directory " + checkExists@b@ .getAbsolutePath() + " is not writable, please set java.io.tempdir to a writable directory");@b@ }@b@@b@ Random ran = new Random();@b@ int x = ran.nextInt(1000000);@b@ File f = new File(s, "camel-tmp-" + x);@b@ int count = 0;@b@@b@ while (!(f.mkdir())) {@b@ ++count;@b@ if (count >= 100)@b@ {@b@ throw new RuntimeException("Camel cannot a temp directory from" + checkExists@b@ .getAbsolutePath() + " 100 times , please set java.io.tempdir to a writable directory");@b@ }@b@@b@ x = ran.nextInt(1000000);@b@ f = new File(s, "camel-tmp-" + x);@b@ }@b@@b@ return f;@b@ }@b@@b@ @Deprecated@b@ public static synchronized void shutdown()@b@ {@b@ if ((defaultTempDir != null) && (defaultTempDir.exists())) {@b@ removeDir(defaultTempDir);@b@ }@b@@b@ if (shutdownHook != null) {@b@ Runtime.getRuntime().removeShutdownHook(shutdownHook);@b@ shutdownHook = null;@b@ }@b@ }@b@@b@ public static void removeDir(File d) {@b@ String[] list = d.list();@b@ if (list == null)@b@ list = new String[0];@b@@b@ String[] arrayOfString1 = list; int i = arrayOfString1.length; for (int j = 0; j < i; ++j) { String s = arrayOfString1[j];@b@ File f = new File(d, s);@b@ if (f.isDirectory())@b@ removeDir(f);@b@ else@b@ delete(f);@b@ }@b@@b@ delete(d);@b@ }@b@@b@ private static void delete(File f) {@b@ if (!(f.delete())) {@b@ if (isWindows())@b@ System.gc();@b@ try@b@ {@b@ Thread.sleep(10L);@b@ }@b@ catch (InterruptedException localInterruptedException) {@b@ }@b@ if (!(f.delete()))@b@ f.deleteOnExit();@b@ }@b@ }@b@@b@ public static boolean renameFile(File from, File to, boolean copyAndDeleteOnRenameFail)@b@ throws IOException@b@ {@b@ if (!(from.exists())) {@b@ return false;@b@ }@b@@b@ boolean renamed = false;@b@ int count = 0;@b@ while ((!(renamed)) && (count < 3)) {@b@ if ((LOG.isDebugEnabled()) && (count > 0)) {@b@ LOG.debug("Retrying attempt {} to rename file from: {} to: {}", new java.lang.Object[] { Integer.valueOf(count), from, to });@b@ }@b@@b@ renamed = from.renameTo(to);@b@ if ((!(renamed)) && (count > 0))@b@ try {@b@ Thread.sleep(1000L);@b@ }@b@ catch (InterruptedException localInterruptedException)@b@ {@b@ }@b@ ++count;@b@ }@b@@b@ if ((!(renamed)) && (copyAndDeleteOnRenameFail))@b@ {@b@ LOG.debug("Cannot rename file from: {} to: {}, will now use a copy/delete approach instead", from, to);@b@ renamed = renameFileUsingCopy(from, to);@b@ }@b@@b@ if ((LOG.isDebugEnabled()) && (count > 0))@b@ LOG.debug("Tried {} to rename file: {} to: {} with result: {}", new java.lang.Object[] { Integer.valueOf(count), from, to, Boolean.valueOf(renamed) });@b@@b@ return renamed;@b@ }@b@@b@ public static boolean renameFileUsingCopy(File from, File to)@b@ throws IOException@b@ {@b@ if (!(from.exists())) {@b@ return false;@b@ }@b@@b@ LOG.debug("Rename file '{}' to '{}' using copy/delete strategy.", from, to);@b@@b@ copyFile(from, to);@b@ if (!(deleteFile(from))) {@b@ throw new IOException("Renaming file from '" + from + "' to '" + to + "' failed: Cannot delete file '" + from + "' after copy succeeded");@b@ }@b@@b@ return true;@b@ }@b@@b@ public static void copyFile(File from, File to)@b@ throws IOException@b@ {@b@ Files.copy(from.toPath(), to.toPath(), new CopyOption[] { StandardCopyOption.REPLACE_EXISTING });@b@ }@b@@b@ public static boolean deleteFile(File file)@b@ {@b@ if (!(file.exists())) {@b@ return false;@b@ }@b@@b@ boolean deleted = false;@b@ int count = 0;@b@ while ((!(deleted)) && (count < 3)) {@b@ LOG.debug("Retrying attempt {} to delete file: {}", Integer.valueOf(count), file);@b@@b@ deleted = file.delete();@b@ if ((!(deleted)) && (count > 0))@b@ try {@b@ Thread.sleep(1000L);@b@ }@b@ catch (InterruptedException localInterruptedException)@b@ {@b@ }@b@ ++count;@b@ }@b@@b@ if ((LOG.isDebugEnabled()) && (count > 0))@b@ LOG.debug("Tried {} to delete file: {} with result: {}", new java.lang.Object[] { Integer.valueOf(count), file, Boolean.valueOf(deleted) });@b@@b@ return deleted;@b@ }@b@@b@ public static boolean isAbsolute(File file)@b@ {@b@ if (isWindows())@b@ {@b@ String path = file.getPath();@b@ if (path.startsWith(File.separator))@b@ return true;@b@ }@b@@b@ return file.isAbsolute();@b@ }@b@@b@ public static boolean createNewFile(File file)@b@ throws IOException@b@ {@b@ if (file.exists())@b@ return false;@b@ try@b@ {@b@ return file.createNewFile();@b@ }@b@ catch (IOException e)@b@ {@b@ if (file.exists())@b@ return true;@b@@b@ throw e;@b@ }@b@ }@b@}