📄 filetools.java
字号:
/*
* This file is part of Caliph & Emir.
*
* Caliph & Emir is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Caliph & Emir is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Caliph & Emir; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Copyright statement:
* --------------------
* (c) 2005 by Werner Klieber (werner@klieber.info)
* http://caliph-emir.sourceforge.net
*/
package at.wklieber.tools;
import javax.swing.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
class ResourceClass {
public String getBaseDir() {
URL base = this.getClass().getResource("/");
String returnValue = base.toExternalForm();
return returnValue;
}
}
public class FileTools {
//static Logger log = Logger.getLogger(FileTools.class);
public static String LINE_BREAK = "\n";
public static final String SEPARATOR = File.separator;
private static int BUFFER_SIZE = 2048;
private static boolean noDebug = false;
private static FileTools fileTools = new FileTools();
private static String currentWorkingDir = null;
/*static {
byte[] b = {Character.LINE_SEPARATOR};
LINE_BREAK = new String(b);
}*/
public static void setNoDebug(boolean noDebug1) {
noDebug = noDebug1;
}
/**
* do not instanciate this class
*/
private FileTools() {
}
/**
* if the input string doesn't end with an directory-seperator
* one is added
*/
public static String setFinalDirectorySlash(String dir) {
if (!dir.endsWith("/") && !dir.endsWith("\\"))
dir += SEPARATOR;
return dir;
}
/**
* replace invalid characters filename that are not allowed in
* filenames. Note: ":" is replaced. so don't use it with absolute paths
* like "c:\test". The same is with "\", "/"
*/
public static String makeValidFilename(String filename1) {
String ret = filename1;
ret = ret.replace(':', '_');
ret = ret.replace('\\', '_');
ret = ret.replace('/', '_');
ret = ret.replace(';', '_');
ret = ret.replace('*', '_');
ret = ret.replace('?', '_');
ret = ret.replace('\"', '_');
ret = ret.replace('>', '_');
ret = ret.replace('<', '_');
ret = ret.replace('|', '_');
return ret;
}
/**
* true if the give file exists
*/
public static boolean existsFile(String filename1) {
boolean returnValue = false;
if (filename1 == null) return returnValue;
try {
String name = removeFileUrlPrefix(filename1);
File f = new File(name);
returnValue = (f.exists() && f.isFile());
if (returnValue) {
return returnValue; //-- exit point -------------
}
} catch (Exception e) {
//log.info("Exception: " + e.getMessage());
//e.printStackTrace();
returnValue = false;
}
// file does not work with files within a jar file
// so invoke the resource Loader to find the file within a jar-file
try {
returnValue = false;
int startPos = filename1.indexOf("!");
if (startPos > -1) {
filename1 = filename1.substring(startPos + 2); // without leading "!/"
//log.debug("LOOK for: " + filename1);
ClassLoader loader = fileTools.getClass().getClassLoader();
URL url = loader.getResource(filename1);
returnValue = (url != null);
} // end if is located in a jar-file
} catch (Exception e) {
//log.error(e);
//e.printStackTrace();
returnValue = false;
}
return returnValue;
}
/**
* true if the give file or dir exists
*/
public static boolean exists(String filename1) {
boolean returnValue = false;
if (filename1 == null) return returnValue;
try {
File f = new File(filename1);
returnValue = f.exists();
} catch (Exception e) {
//log.info("Exception: " + e.getMessage());
//e.printStackTrace();
returnValue = false;
}
return returnValue;
}
/**
* if the input string ends with an directory-seperator it is removed
*/
public static String removeFinalDirectorySlash(String dir1) {
String ret = dir1;
if (ret.endsWith("/") || ret.endsWith("\\")) {
int len = ret.length();
ret = ret.substring(0, len - 1);
}
return ret;
}
/**
* create the directory "dir1". Recursive Directory generation is supported.
* e.g. Directory "c:\temp" exists. dir1 = "C:\temp\dir1\dir2\dir3\" is allowed.
* if the String does not end with an directory-separator it is assumed that it
* is a file. e.g c:\temp\dira\dirb\test creates c:\temp\dira\dirb\
*/
public static void makeDirectory(String dir1) {
if ((dir1 == null) || (dir1.trim().length() == 0)) {
return;
}
dir1 = removeFileUrlPrefix(dir1);
String directory = resolvePath(dir1);
if (!directory.endsWith("\\") && !directory.endsWith("/")) {
StringTokenizer tokens = new StringTokenizer(directory, "/\\", false);
directory = "";
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (tokens.hasMoreTokens()) {
if (directory.length() > 0) {
directory += "/";
}
directory += token;
}
} // end while
} // end if last entry is a file
File fileDescr = new File(directory);
try {
if (fileDescr.exists()) {
if (fileDescr.isFile()) {
//log.error("Unable to create directory \"" + directory + "\" because it is a file.");
}
// now it is a directory that already exists
return;
}
if (!fileDescr.mkdirs()) {
//log.warn("Unable to create directory \"" + directory + "\".");
}
} catch (Exception e) {
//log.error(e);
}
} // end method
public static void deleteDir(String a_dir) {
File f = new File(a_dir);
if (f.exists() && f.isDirectory()) {
f.delete();
} else {
// log.error("Unable do delete file: \"" + a_dir + "\"");
}
}
/**
* if the path "relPath" is a relative path (not begins with a seperator or x:)
* then the abs_path information is added,
* so the out put is absPath + relPath
*/
public static String relative2absolutePath(String relPath, String absPath, boolean isFile) {
if (relPath == null)
return relPath;
if (absPath == null) {
absPath = "";
}
boolean doublePoint = false;
if ((relPath.length() >= 2) && (relPath.charAt(1) == ':'))
doublePoint = true;
//System.out.println("char: <" + relPath.charAt(1) + ">, bool: " + doublePoint);
String ret = relPath;
if (!isFile)
relPath = setFinalDirectorySlash(relPath);
if (!doublePoint && !relPath.startsWith("\\") && !relPath.startsWith("/")) {
if (relPath.startsWith("./")) {
relPath = relPath.substring(2);
}
ret = setFinalDirectorySlash(absPath) + relPath;
}
return ret;
}
public static String relative2absolutePath(String relPath, String absPath) {
return relative2absolutePath(relPath, absPath, false);
}
/**
* make an absolute path depending on the working directory
* if the last entry specifies a directory that exists, a separator is added
* if isDirectory1=true, a separator is always added
* addapt the /, \ to /
* example: ..\..\dummy.txt -> c:\test\dummy.txt
* folder\dummy.txt -> c:\folder\dummy.txt
*
* @param filename1 Filename to check
* @param isDirectory1 if true, at the last entry in the path is interpeted
* as Directory (a slash will be added).
*/
public static String resolvePath(String filename1, boolean isDirectory1) {
String ret = filename1.trim();
try {
if (ret == null || ret.length() == 0) {
return "";
}
// if UNIX: convert X:\something -> /something
if ((File.separatorChar == '/') && (ret.length() >= 2) && (ret.charAt(1) == ':')) {
ret = ret.substring(2);
}
if (!hasUrlPrefix(ret)) {
File f = new File(ret);
// cannonicalPAth do not work with uri
// file://c:/temp -> d:\workingdir\file://c:/temp
ret = f.getCanonicalPath();
if (isDirectory1 || f.isDirectory()) {
ret = setFinalDirectorySlash(ret);
}
}
ret = ret.replace('\\', '/');
// if it is a file, try to locate it. Even if its in an jar-archive
if (!isDirectory1 && !existsFile(ret)) {
// try to load using the classloader
ret = filename1;
/*int baseDirLength = getWorkingDirectory().length();
log.debug("Working directory: \"" + getWorkingDirectory() + "\"");
// make the absolute ret relative, so the getResourse can be used
if ((baseDirLength > 0) && (ret.length() > baseDirLength) && (ret.startsWith(getWorkingDirectory()))) {
ret = "/" + ret.substring(baseDirLength);
}*/
//log.debug("Looking with getResource for <" + ret + ">");
URL fileUrl = fileTools.getClass().getResource(ret);
//System.out.println("URL is null :<" + (fileUrl == null) + ">, File: " + ret);
if (fileUrl != null) {
//log.debug("URL tostring:<" + fileUrl.toString() + ">, exist: " + existsFile(fileUrl.toString()));
//log.debug("URL file :<" + fileUrl.getFile() + ">, exist: " + existsFile(fileUrl.getFile()));
//log.debug("URL ref :<" + fileUrl.getRef() + ">, exist: " + existsFile(fileUrl.getRef()));
ret = fileUrl.toString();
}
}
} catch (Exception e) {
//Console.exitOnException(e);
e.printStackTrace();
System.err.println(e);
}
return ret;
}
public static String resolvePath(String filename1) {
//default is no directory.
// but if the filename ends with a slash, it is interpreded as path
if (filename1 == null) {
filename1 = "";
}
String filename = filename1.trim();
boolean isPath = ((filename.endsWith("/")) || (filename.endsWith("\\")));
return resolvePath(filename1, isPath);
}
/**
* input is the string representation of a file, output is the java url class of this.
* Note: if the filenName is relative, the class.getResource is involved to retrieve the
* location
*/
public static URL getFileURL(String fileName1, URL default1) {
URL returnValue = default1;
if (fileName1 == null) return returnValue;
// first check, wheter it is already a valid url
try {
returnValue = new URL(setUrlPrefix(fileName1));
return returnValue;
} catch (MalformedURLException e) {
//log.info(e);
returnValue = default1;
}
try {
String urlString = resolvePath(fileName1);
returnValue = new URL(setUrlPrefix(urlString));
} catch (MalformedURLException e) {
//log.error(e);
returnValue = default1;
}
return returnValue;
}
/**
* returns the absolute path of the currend working directory
*
* @return
*/
public static String getWorkingDirectory() {
if (currentWorkingDir == null) {
File f = new File("");
currentWorkingDir = setFinalDirectorySlash(f.getAbsolutePath());
}
return currentWorkingDir;
}
/**
* set a new working directory
*/
public static void setWorkingDirectory(String workingDir) {
if (workingDir != null) {
File f = new File(workingDir);
currentWorkingDir = setFinalDirectorySlash(f.getAbsolutePath());
} else {
currentWorkingDir = null;
}
}
/**
* returns the absolute path of the temp directory
*
* @return
*/
public static String getTempDirectory() {
return setFinalDirectorySlash(System.getProperty("java.io.tmpdir"));
}
/**
* returns the absolute path of the user home directory
*
* @return
*/
public static String getUserHomeDirectory() {
return setFinalDirectorySlash(System.getProperty("user.home"));
}
/**
* returns the absolute path of the base dir where the class is located (classpath).
*
* @return
*/
public static String getResourceBaseDirectory() {
ResourceClass res = new ResourceClass();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -