📄 fileutility.java
字号:
final FileOutputStream output = new FileOutputStream(destination);
IOUtility.copy(input, output);
IOUtility.shutdownStream(input);
IOUtility.shutdownStream(output);
}
/**
* Normalize a path.
* Eliminates "/../" and "/./" in a string. Returns <code>null</code> if the ..'s went past the
* root.
* Eg:
* <pre>
* /foo// --> /foo/
* /foo/./ --> /foo/
* /foo/../bar --> /bar
* /foo/../bar/ --> /bar/
* /foo/../bar/../baz --> /baz
* //foo//./bar --> /foo/bar
* /../ --> null
* </pre>
*
* @param path the path to normalize
* @return the normalized String, or <code>null</code> if too many ..'s.
*/
public static String normalize(final String path) {
String normalized = path;
// Resolve occurrences of "//" in the normalized path
while (true) {
int index = normalized.indexOf("//");
if (index < 0)
break;
normalized = normalized.substring(0, index) + normalized.substring(index + 1);
}
// Resolve occurrences of "/./" in the normalized path
while (true) {
int index = normalized.indexOf("/./");
if (index < 0)
break;
normalized = normalized.substring(0, index) + normalized.substring(index + 2);
}
// Resolve occurrences of "/../" in the normalized path
while (true) {
int index = normalized.indexOf("/../");
if (index < 0)
break;
if (index == 0)
return null; // Trying to go outside our context
int index2 = normalized.lastIndexOf('/', index - 1);
normalized = normalized.substring(0, index2) + normalized.substring(index + 3);
}
// Return the normalized path that we have completed
return normalized;
}
/**
* Will concatenate 2 paths, dealing with <code>..</code>
* <p>Eg.,<br />
* <code>/a/b/c</code> + <code>d</code> = <code>/a/b/d</code><br />
* <code>/a/b/c</code> + <code>../d</code> = <code>/a/d</code><br />
* </p>
*
* Thieved from Tomcat sources...
*
* @return The concatenated paths, or null if error occurs
*/
public static String catPath(final String lookupPath, final String path) {
// Cut off the last slash and everything beyond
int index = lookupPath.lastIndexOf("/");
String lookup = lookupPath.substring(0, index);
String pth = path;
// Deal with .. by chopping dirs off the lookup path
while (pth.startsWith("../")) {
if (lookup.length() > 0) {
index = lookup.lastIndexOf("/");
lookup = lookup.substring(0, index);
}
else {
// More ..'s than dirs, return null
return null;
}
index = pth.indexOf("../") + 3;
pth = pth.substring(index);
}
return new StringBuffer(lookup).append("/").append(pth).toString();
}
/**
* Resolve a file <code>filename</code> to it's canonical form. If <code>filename</code> is
* relative (doesn't start with <code>/</code>), it will be resolved relative to
* <code>baseFile</code>, otherwise it is treated as a normal root-relative path.
*
* @param baseFile Where to resolve <code>filename</code> from, if <code>filename</code> is
* relative.
* @param filename Absolute or relative file path to resolve.
* @return The canonical <code>File</code> of <code>filename</code>.
*/
public static File resolveFile(final File baseFile, String filename) {
String filenm = null;
if ('/' != File.separatorChar) {
filenm = filename.replace('/', File.separatorChar);
}
if ('\\' != File.separatorChar) {
filenm = filename.replace('\\', File.separatorChar);
}
// deal with absolute files
if (filenm.startsWith(File.separator)) {
File file = new File(filenm);
try {
file = file.getCanonicalFile();
}
catch (final IOException ioe) {}
return file;
}
// FIXME: I'm almost certain this // removal is unnecessary, as getAbsoluteFile() strips
// them. However, I'm not sure about this UNC stuff. (JT)
final char[] chars = filename.toCharArray();
final StringBuffer sb = new StringBuffer();
//remove duplicate file separators in succession - except
//on win32 at start of filename as UNC filenames can
//be \\AComputer\AShare\myfile.txt
int start = 0;
if ('\\' == File.separatorChar) {
sb.append(filenm.charAt(0));
start++;
}
for (int i = start; i < chars.length; i++) {
final boolean doubleSeparator = File.separatorChar == chars[i] && File.separatorChar == chars[i - 1];
if (!doubleSeparator) {
sb.append(chars[i]);
}
}
filenm = sb.toString();
//must be relative
File file = (new File(baseFile, filenm)).getAbsoluteFile();
try {
file = file.getCanonicalFile();
}
catch (final IOException ioe) {}
return file;
}
/**
* Delete a file. If file is directory delete it and all sub-directories.
*/
public static void forceDelete(final String file) throws IOException {
forceDelete(new File(file));
}
/**
* Delete a file. If file is directory delete it and all sub-directories.
*/
public static void forceDelete(final File file) throws IOException {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
if (false == file.delete()) {
final String message = "File " + file + " unable to be deleted.";
throw new IOException(message);
}
}
}
/**
* Recursively delete a directory.
*/
public static void deleteDirectory(final String directory) throws IOException {
deleteDirectory(new File(directory));
}
/**
* Recursively delete a directory.
*/
public static void deleteDirectory(final File directory) throws IOException {
if (!directory.exists()) {
return;
}
cleanDirectory(directory);
if (false == directory.delete()) {
throw new IOException("Directory " + directory + " unable to be deleted.");
}
}
/**
* Clean a directory without deleting it.
*/
public static void cleanDirectory(final String directory) throws IOException {
cleanDirectory(new File(directory));
}
/**
* Clean a directory without deleting it.
*/
public static void cleanDirectory(final File directory) throws IOException {
if (!directory.exists()) {
final String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
final String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
final File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
final File file = files[i];
FileUtility.forceDelete(file);
}
}
/**
* Replace substrings of one string with another string and return altered string.
*
* @param original input string
* @param oldString the substring section to replace
* @param newString the new substring replacing old substring section
* @return converted string
*/
private static String replaceSubString(final String original, final String oldString, final String newString) {
final StringBuffer sb = new StringBuffer();
int end = original.indexOf(oldString);
int start = 0;
final int stringSize = oldString.length();
while (end != -1) {
sb.append(original.substring(start, end));
sb.append(newString);
start = end + stringSize;
end = original.indexOf(oldString, start);
}
end = original.length();
sb.append(original.substring(start, end));
return sb.toString();
}
/**
* Recursively count size of a directory.
*
* @return size of directory in bytes.
*/
public static long sizeOfDirectory(final String directory) {
return sizeOfDirectory(new File(directory));
}
/**
* Recursively count size of a directory.
*
* @return size of directory in bytes.
*/
public static long sizeOfDirectory(final File directory) {
if (!directory.exists()) {
final String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
final String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
long size = 0;
final File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
final File file = files[i];
if (file.isDirectory()) {
size += sizeOfDirectory(file);
}
else {
size += file.length();
}
}
return size;
}
/**
* Get an unique path file
* @param basePath base path
* @param subPath sub directory name
* @return an unique path file that not exists
*/
public static File getUniquePath(String basePath, String subPath) {
File resultPath = new File(basePath, subPath);
int counter = 1;
while (resultPath.exists()) {
resultPath = new File(basePath, subPath + counter);
counter++;
}
return resultPath;
}
/**
* Get an unique file
* @param dir the path where the file in
* @param originFile origin file name
* @return an unique file that not exists
*/
public static File getUniqueFile(String dir, String originFile) {
String originFileName = removeExtension(originFile);
String originFileExt = getExtension(originFile);
File resultFile = new File(dir, originFile);
int counter = 1;
while (resultFile.exists()) {
resultFile = new File(dir, new StringBuffer(originFileName).append(counter).append(".").append(originFileExt).toString());
counter++;
}
return resultFile;
}
/**
* 将内容存储为文件
* @param String content 存储的内容
* @param String pathName 存储的路径
* @param String fileName 存储的文件名
* @throws Exception 异常
* @author windy
*/
public static void saveToFile(String content, String pathName, String fileName)
throws Exception
{
try
{
createDir(pathName);
FileOutputStream fileoutputstream = new FileOutputStream(pathName + fileName);
byte abyte0[] = content.getBytes();
fileoutputstream.write(abyte0);
fileoutputstream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
/**
* 创建新的目录
* @param String pathName
* @author windy
*/
public static void createDir(String pathName)
{
File file = new File(pathName);
if(!file.exists())
file.mkdirs();
}
/**
* 判断文件是否存在
* @param String fileName
* @return boolean 文件是否存在,若存在返回true,否则返回false
*
* @author windy
*/
public static boolean isExist(String fileName){
File file = new File(fileName);
return file.exists();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -