文件操作工具类
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import java.io.*;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class FileUtil {
public static boolean checkExist(String sFileName) {
boolean result;
try {
File f = new File(sFileName);
result = f.exists() && f.isFile();
} catch (Exception e) {
result = false;
}
return result;
}
public static boolean createDirectory(String dir) {
File f = new File(dir);
if (!f.exists()) {
f.mkdirs();
return true;
}
return false;
}
public static void createNewFile(String fileDirectoryAndName, String fileContent) {
if (!checkExist(fileDirectoryAndName)) {
try {
new File(fileDirectoryAndName).createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (fileContent != null && fileContent.length() > 0)
write(fileContent, fileDirectoryAndName, true);
}
}
public static boolean saveFileByPhysicalDir(String physicalPath, InputStream inputStream, boolean isbool) {
boolean flag = false;
if (checkExist(physicalPath)) {
try {
OutputStream os = new FileOutputStream(physicalPath, isbool);
int readBytes;
byte buffer[] = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, readBytes);
}
os.close();
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
public static boolean write(String tivoliMsg, String logFileName, boolean isbool) {
boolean flag = false;
try {
if (checkExist(logFileName)) {
byte[] bMsg = tivoliMsg.getBytes("UTF-8");
FileOutputStream fOut = new FileOutputStream(logFileName, isbool);
fOut.write(bMsg);
fOut.close();
flag = true;
} else {
System.out.println("FileUtil.write:文件不存在。" + logFileName);
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
public static void writeLog(String logFile, String batchId, String exceptionInfo) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE);
Object args[] = {df.format(new Date()), batchId, exceptionInfo};
String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args);
try {
File logfile = new File(logFile);
if (!logfile.exists()) {
logfile.createNewFile();
}
FileWriter fw = new FileWriter(logFile, true);
fw.write(fmtMsg);
fw.write(System.getProperty("line.separator"));
fw.flush();
fw.close();
} catch (Exception ignored) {
}
}
public static String readTextFile(String realPath, String charsetName) {
StringBuilder txt = new StringBuilder();
if (checkExist(realPath)) {
BufferedReader br = null;
try {
if (StringUtils.isBlank(charsetName)) {
charsetName = new BytesEncodingDetect().getFileEncoding(realPath);
}
br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), charsetName));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String temp;
try {
if (br != null) {
while ((temp = br.readLine()) != null) {
txt.append(temp);
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return txt.toString();
}
public static String resolveCode(String path) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] head = new byte[3];
try {
inputStream.read(head);
} catch (IOException e) {
e.printStackTrace();
}
String code = "GB2312";
if (head[0] == -1 && head[1] == -2)
code = "UTF-16";
else if (head[0] == -2 && head[1] == -1)
code = "Unicode";
else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
code = "UTF-8";
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return code;
}
public static void copyFile(String srcFile, String targetFile) {
if (checkExist(srcFile)) {
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
try {
fi = new FileInputStream(srcFile);
fo = new FileOutputStream(targetFile);
in = fi.getChannel();
out = fo.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fi != null) {
fi.close();
}
if (in != null) {
in.close();
}
if (fo != null) {
fo.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void copyDir(String sourceDir, String destDir) {
File sourceFile = new File(sourceDir);
String tempSource;
String tempDest;
String fileName;
if (new File(destDir).getParentFile().isDirectory()) {
new File(destDir).mkdirs();
}
File[] files = sourceFile.listFiles();
if (files != null) {
for (File file : files) {
fileName = file.getName();
tempSource = sourceDir + "/" + fileName;
tempDest = destDir + "/" + fileName;
if (file.isFile()) {
copyFile(tempSource, tempDest);
} else {
copyDir(tempSource, tempDest);
}
}
}
}
public static void renameFile(String srcFile, String targetFile) {
copyFile(srcFile, targetFile);
deleteFromName(srcFile);
}
public static long getSize(String sFileName) {
long lSize = -1;
try {
if (checkExist(sFileName)) {
File f = new File(sFileName);
if (f.canRead()) {
lSize = f.length();
} else {
lSize = -1;
}
}
} catch (Exception e) {
lSize = -1;
}
return lSize;
}
public static boolean deleteFromName(String sFileName) {
boolean bReturn = true;
if (checkExist(sFileName)) {
File oFile = new File(sFileName);
if (!oFile.delete())
bReturn = false;
}
return bReturn;
}
public static boolean deleteDirectory(File dir) {
if (!dir.exists()) {
return false;
}
File[] entries = dir.listFiles();
if (entries != null) {
for (File entry : entries) {
if (entry.isDirectory()) {
if (!deleteDirectory(entry)) {
return false;
}
} else {
if (!entry.delete()) {
return false;
}
}
}
}
return dir.delete();
}
public static void unZip(String sToPath, String sZipFile) {
if (null == sToPath || ("").equals(sToPath.trim())) {
File objZipFile = new File(sZipFile);
sToPath = objZipFile.getParent();
}
ZipFile zfile = null;
try {
zfile = new ZipFile(sZipFile);
} catch (IOException e) {
e.printStackTrace();
}
Enumeration<? extends ZipEntry> zList = zfile != null ? zfile.entries() : null;
ZipEntry ze;
byte[] buf = new byte[1024];
while (zList != null && zList.hasMoreElements()) {
ze = zList.nextElement();
if (ze.isDirectory()) {
continue;
}
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(sToPath, ze.getName())));
} catch (Exception e) {
e.printStackTrace();
}
InputStream is;
try {
is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
if (os != null) {
os.write(buf, 0, readLen);
}
}
is.close();
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (zfile != null) {
zfile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static File getRealFileName(String baseDir, String absFileName) {
File ret;
ArrayList dirs = new ArrayList();
StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator"));
while (st.hasMoreTokens()) {
dirs.add(st.nextToken());
}
ret = new File(baseDir);
if (dirs.size() > 1) {
for (int i = 0; i < dirs.size() - 1; i++) {
ret = new File(ret, (String) dirs.get(i));
}
}
if (!ret.exists())
ret.mkdirs();
ret = new File(ret, (String) dirs.get(dirs.size() - 1));
return ret;
}
public static void zip(String srcPathName, String finalFile, String strIncludes, String strExcludes) {
File srcdir = new File(srcPathName);
if (!srcdir.exists()) {
throw new RuntimeException(srcPathName + "不存在!");
}
if (finalFile == null || "".equals(finalFile)) {
finalFile = srcPathName + ".zip";
}
File zipFile = new File(finalFile);
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
FileSet fileSet = new FileSet();
fileSet.setProject(prj);
fileSet.setDir(srcdir);
if (strIncludes != null && !"".equals(strIncludes)) {
fileSet.setIncludes(strIncludes);
}
if (strExcludes != null && !"".equals(strExcludes)) {
fileSet.setExcludes(strExcludes);
}
zip.addFileset(fileSet);
zip.execute();
}
}