上传文件(图片):
<resourceHardiskPath>/usr/local/portalMS/jboss5/server/default/deploy/portal.war/</resourceHardiskPath>
/**
* 设置频道文件名全路径
*
* @param fileName
* 页面请求的文件名
* @param index
* 资源序号
* @return
*/
private String setFilePath(String fileName, String index) //fileName:part.jpg index:0
{
// 从配置文件读取根路径
String rootUrl = XMLFactory.getValueString("publish.resourceHardiskPath");
StringBuffer filePathSB = new StringBuffer();
filePathSB.append(rootUrl);
filePathSB.append(File.separator);
filePathSB.append(Constants.IEPG_LOGO_PATH.getStringValue());
filePathSB.append(File.separator);
// 频道文件名
filePathSB.append(fileName.substring(0, fileName.lastIndexOf(".")));
filePathSB.append("_");
filePathSB.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString());
filePathSB.append(index);
filePathSB.append(fileName.substring(fileName.lastIndexOf(".")));
// 频道文件名全路径
return filePathSB.toString();
// /usr/local/portalMS/jboss5/server/default/deploy/portal.war/\logo\part_201402201451080.jpg
}
resources.get(i) =[D:\tomcat_portal\work\Catalina\localhost\portalMS\upload__26cdfb2f_1444df1297a__8000_00000008.tmp]
filePath:/usr/local/portalMS/jboss5/server/default/deploy/portal.war/\logo\part_201402201451080.jpg
FileUtil.uploadResource(resources.get(i), filePath, true);
FileUtil:
package com.xxxxxx.dhm.portalMS.common.util;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.Enumeration;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import com.xxxxxx.dhm.common.config.impl.XMLFactory;
import com.xxxxxx.dhm.portalMS.common.Constants;
import com.xxxxxx.dhm.portalMS.common.DebugLogHelper;
import com.xxxxxx.dhm.portalMS.common.SerConstants;
import com.xxxxxx.dhm.portalMS.exception.PortalMSException;
/**
* FileUtil.java 文件操作工具类
*
* @author kanxiaohui
*/
public class FileUtil
{
private static final DebugLogHelper logger = new DebugLogHelper(FileUtil.class);
private static String MESSAGE = "";
public static final char separator = '\\';
public static final char linux_separator = '/';
private static final int BUFFER_SIZE = 16 * 1024;
private static final long VIRTUAL_MEMORY_SIZE = 512 * 1024 * 1024;
/**
* 读取文件的内容(文件的格式仅限.html、.css、.js)
* @param filePath
* @return
* @throws IEPGMException
* @return String
* @throws Exception
* @exception throws
*/
public static String readFileContent(String filePath, String encode)
throws Exception
{
BufferedInputStream bis = null;
StringBuffer sb = new StringBuffer();
try
{
bis = new BufferedInputStream(new FileInputStream(
new File(filePath)));
byte[] buf = new byte[1024 * 10];
int len = -1;
while ((len = bis.read(buf)) != -1)
{
sb.append(new String(buf, 0, len, encode));
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("read file content error. reason:" + e);
throw new IOException(e);
}
finally
{
try
{
bis.close();
}
catch (Exception e)
{
logger.excepFuncDebugLog("read file content error. reason:" + e);
throw new Exception(e);
}
}
return sb.toString();
}
/**
* 内容输出到文件
* @param content 内容
* @param filePath 文件路径
* @param encode 编码
* @throws Exception
* @return void
* @exception throws
*/
public static void stringWriteToFile(String content, String filePath,
String encode) throws Exception
{
File indexTemplateFile = new File(filePath);
if (indexTemplateFile.exists())
{
boolean flag = indexTemplateFile.delete();
if (!flag)
{
logger.excepFuncDebugLog("delete file is failed");
}
}
try
{
indexTemplateFile.createNewFile();
}
catch (IOException e1)
{
logger.excepFuncDebugLog("creat file is failed. filePath = " + filePath);
throw e1;
}
BufferedOutputStream out = null;
try
{
out = new BufferedOutputStream(new FileOutputStream(
indexTemplateFile));
out.write(content.getBytes(encode));
}
catch (Exception e)
{
logger.excepFuncDebugLog("The content is written to the file failed. filePath = "
+ filePath);
throw e;
}
finally
{
try
{
out.close();
}
catch (Exception e)
{
logger.excepFuncDebugLog("Closes the output stream failure . ");
throw (e);
}
}
}
/**
* 保存文件输入流到指定目录和文件名的文件实体中
*
* @param destFileName 目标文件名
* @param in 源文件输入流
* @param destFilePath 目标文件路径
* @throws Exception
*/
public static void saveFile(String destFileName, InputStream in,
String destFilePath) throws IOException
{
OutputStream bos = null;// 建立一个保存文件的输出流
try
{
destFilePath = trimFilePath(destFilePath) + "/" + destFileName;
bos = new FileOutputStream(destFilePath, false);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1)
{
bos.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (bos != null)
{
bos.close();
}
if (in != null)
{
in.close();
}
}
}
/**
* 保存文件
*
* @param destFile 目标文件完整路径
* @param in 源文件输入流
* @throws Exception
*/
public static void saveFile(File destFile, InputStream in)
throws IOException
{
OutputStream bos = null;
try
{
bos = new FileOutputStream(destFile, false);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1)
{
bos.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (bos != null)
{
bos.close();
}
if (in != null)
{
in.close();
}
}
}
/**
* zip文件解压缩
*
* @param zipFileName 文件完整路径
* @param outputDirectory 解压保存路径
* @param isCover 是否重名覆盖
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static void unzip(String zipFileName, String outputDirectory,
boolean isCover) throws IOException
{
logger.excepFuncDebugLog("To extract the files :" + zipFileName
+ SerConstants.COLON + outputDirectory);
ZipFile zipFile = new ZipFile(zipFileName);
try
{
Enumeration<ZipEntry> e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
InputStream in = null;
FileOutputStream out = null;
while (e.hasMoreElements())
{
zipEntry = e.nextElement();
if (zipEntry.isDirectory())
{
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
if (!f.exists())
{
if (!f.mkdirs())
{
zipFile.close();
throw new IOException(
"Failed to create the directory!");
}
}
}
else
{
String fileName = zipEntry.getName();
fileName = fileName.replace(separator, File.separatorChar);
fileName = fileName.replace(linux_separator,
File.separatorChar);
if (fileName.indexOf(File.separatorChar) != -1)
{
createDirectory(outputDirectory, getPath(fileName));
fileName = fileName.substring(fileName.lastIndexOf(separator) + 1,
fileName.length());
}
File f = new File(outputDirectory + File.separator
+ zipEntry.getName());
if (f.exists())
{
if (isCover)
{
// 如果要覆盖,先删除原有文件
FileUtils.delete(f);
}
else
{
// 如果不覆盖,不做处理
continue;
}
// continue;
}
if (!f.createNewFile())
{
zipFile.close();
throw new IOException("Creating file failed !");
}
try
{
in = zipFile.getInputStream(zipEntry);
out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1)
{
out.write(by, 0, c);
}
}
catch (IOException ex)
{
throw ex;
}
finally
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
}
}
}
catch (IOException e)
{
throw e;
}
finally
{
zipFile.close();
}
}
@SuppressWarnings("unchecked")
public static void unzipNoDir(String zipFileName, String outputDirectory,
boolean isCover) throws IOException
{
logger.excepFuncDebugLog("To extract the files :" + zipFileName
+ SerConstants.COLON + outputDirectory);
ZipFile zipFile = new ZipFile(zipFileName);
try
{
Enumeration<ZipEntry> e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
InputStream in = null;
FileOutputStream out = null;
while (e.hasMoreElements())
{
zipEntry = e.nextElement();
if (zipEntry.isDirectory())
{
}
else
{
// String fileName = zipEntry.getName();
String newName = zipEntry.getName()
.substring(zipEntry.getName().lastIndexOf('/') + 1,
zipEntry.getName().length());
File f = new File(outputDirectory + File.separator
+ newName);
if (f.exists())
{
if (isCover)
{
// 如果要覆盖,先删除原有文件
FileUtils.delete(f);
}
else
{
// 如果不覆盖,不做处理
continue;
}
}
if (!f.createNewFile())
{
zipFile.close();
throw new IOException("Creating file failed !");
}
try
{
in = zipFile.getInputStream(zipEntry);
out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1)
{
out.write(by, 0, c);
}
}
catch (IOException ex)
{
throw ex;
}
finally
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
}
}
}
catch (IOException e)
{
throw e;
}
finally
{
zipFile.close();
}
}
public static String trimFilePath(String filePath)
{
if (filePath == null || filePath.trim().length() == 0)
{
return "";
}
if (filePath.endsWith(String.valueOf(separator)))
{
filePath = filePath.substring(0, filePath.length() - 1);
}
return filePath;
}
private static void createDirectory(String directory, String subDirectory)
throws IOException
{
String dir[];
File fl = new File(directory);
if (subDirectory.equals("") && fl.exists() != true)
{
if (fl.mkdirs())
{
throw new IOException("Creating file failed !" + directory);
}
}
else if (!subDirectory.equals(""))
{
dir = subDirectory.replace(separator, File.separatorChar)
.split("\\\\");
StringBuffer sBuffer = new StringBuffer(directory);
for (int i = 0; i < dir.length; i++)
{
File subFile = new File(sBuffer.toString() + File.separator
+ dir[i]);
if (!subFile.exists())
{
if (!subFile.mkdirs())
{
throw new IOException("Creating file failed !"
+ subDirectory);
}
}
sBuffer.append(separator + dir[i]);
}
}
}
/**
* 当文件路径包含文件名时,截取该文件所在文件夹路径
*
* @param fileName
* @return
*/
public static String getPath(String fileName)
{
if (fileName.lastIndexOf(File.separator) >= 0)
{
return fileName.substring(0, fileName.lastIndexOf(File.separator));
}
return fileName;
}
/**
* 把字符串写入指定文件
*
* @param fileName
* @param content
*/
public static void writeStringToFile(String fileName, String content)
throws IOException
{
File file = new File(fileName);
if (file.exists())
{
FileUtils.delete(file);
}
// if (file.createNewFile()) {
// throw new IOException("创建文件:" + fileName + "失败!");
// }
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.close();
}
/**
* 获取某文件路径的跟路径
*
* @param fileName
* @return
*/
public static String getRootPath(String fileName)
{
if (fileName.lastIndexOf("/") >= 0)
{
return "/" + fileName.split("/")[1];
}
return fileName;
}
/**
* 删除指定的文件
* @param file
*/
public static void deleteFile(File file) throws IOException
{
if (file == null || !file.exists())
{
return;
}
if (file.isDirectory())
{
deleteDirectory(file);
}
else
{
if (!file.delete())
{
logger.excepFuncDebugLog("deleteFile Delete file failed :"
+ file.getAbsolutePath());
}
}
}
/**
* 删除指定的目录
* @param directory
* @throws IOException
*/
public static void deleteDirectory(File directory) throws IOException
{
String[] subFiles = directory.list();
for (int i = 0; i < subFiles.length; i++)
{
File subFile = new File(directory.getAbsolutePath()
+ File.separator + subFiles[i]);
deleteFile(subFile);
}
if (!directory.delete())
{
logger.excepFuncDebugLog("deleteDirectory Delete the specified directory failed :"
+ directory.getAbsolutePath());
}
}
/**
* 获取旧图片全路径
* @param filePath 图片的路径
* @param imageUrl 数据库中保存的图片路径
* @return
*/
public static String getOldResourcePath(String filePath, String imageUrl)
{
int imageIndex = 0;
int imageIndex2 = 0;
int pathIndex = 0;
int pathIndex2 = 0;
if (imageUrl != null && !imageUrl.equals(""))
{
imageIndex = imageUrl.lastIndexOf("\\");
imageIndex2 = imageUrl.lastIndexOf("/");
imageIndex = (imageIndex > imageIndex2 ? imageIndex : imageIndex2);
}
if (filePath != null && !filePath.equals(""))
{
pathIndex = filePath.lastIndexOf("\\");
pathIndex2 = filePath.lastIndexOf("/");
pathIndex = (pathIndex > pathIndex2 ? pathIndex : pathIndex2);
}
StringBuffer oldImagePath = new StringBuffer();
if (pathIndex > 0)
{
oldImagePath.append(filePath.substring(0, pathIndex));
}
else
{
oldImagePath.append(filePath);
}
oldImagePath.append(File.separator);
if (imageIndex > 0)
{
oldImagePath.append(imageUrl.substring(imageIndex + 1));
}
else
{
oldImagePath.append(imageUrl);
}
return oldImagePath.toString();
}
/**
* 删除旧图片
* @param fullFilePath 删除图片的全路径
*/
public static void delOldResource(String fullFilePath)
{
if (fullFilePath != null && !fullFilePath.equals(""))
{
File outFile = new File(fullFilePath);
if (outFile.exists())
{
if (!outFile.delete())
{
logger.excepFuncDebugLog("delOldResource Remove a resource file failed :"
+ fullFilePath);
}
}
}
}
/**
* 资源上传的处理方法
* @param file 上传的文件实体
* @param cover 是否重名覆盖 true -- 是,false -- 否
* @throws PortalMSException
*/
public static void uploadResource(File file, String path, Boolean cover)
throws PortalMSException
{
if (file == null || path == null || path.equals(""))
{
return;
}
File outFile = null;
try
{
outFile = new File(path);
String pathName = FileUtil.getPath(outFile.getPath());
FileMgrTools.createFolder(pathName);
// 如果有同名文件
if (outFile.exists())
{
// 如果选择同名覆盖
if (cover)
{
org.apache.commons.io.FileUtils.forceDelete(outFile);
}
else
{// 否则退出操作
return;
}
}
else
{
if (!outFile.createNewFile())
{
throw new PortalMSException(
Constants.ERROR_CODE_NODE_RESOURCE_FIND.getLongValue(),
new IOException("Creating file failed !"));
}
}
// 创建源文件输入流
FileInputStream in = new FileInputStream(file);
// 保存输入流到指定文件路径
FileUtil.saveFile(outFile, in);
}
catch (Exception e)
{
e.printStackTrace();
throw new PortalMSException(
Constants.ERROR_CODE_NODE_RESOURCE_UPLOAD.getLongValue(), e);
}
}
/**
* 复制单个文件
*
* @param srcFileName 待复制的文件名
* @param descFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName,
boolean overlay)
{
File srcFile = new File(srcFileName);
// 判断源文件是否存在
if (!srcFile.exists())
{
MESSAGE = "source file:" + srcFileName + "not exist!";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
else if (!srcFile.isFile())
{
MESSAGE = "Copy file failed ,source file:" + srcFileName
+ "Is not a file !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
// 判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists())
{
// 如果目标文件存在并允许覆盖
if (overlay)
{
// 删除已经存在的目标文件,无论目标文件是目录还是单个文件
boolean b = new File(destFileName).delete();
if (b)
{
logger.excepFuncDebugLog("Successfully deleted ...");
}
}
}
else
{
// 如果目标文件所在目录不存在,则创建目录
if (!destFile.getParentFile().exists())
{
// 目标文件所在目录不存在
if (!destFile.getParentFile().mkdirs())
{
// 复制文件失败:创建目标文件所在目录失败
return false;
}
}
}
// 复制文件
int byteread = 0; // 读取的字节数
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
while ((byteread = in.read(buffer)) != -1)
{
out.write(buffer, 0, byteread);
}
return true;
}
catch (FileNotFoundException e)
{
return false;
}
catch (IOException e)
{
return false;
}
finally
{
try
{
if (out != null)
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
if (in != null)
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 复制整个目录的内容
*
* @param srcDirName 待复制目录的目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName,
boolean overlay)
{
// 判断源目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists())
{
MESSAGE = "Copy directory failed :source directory" + srcDirName
+ "no exist!";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
else if (!srcDir.isDirectory())
{
MESSAGE = "Copy directory failed :" + srcDirName
+ "Is not a directory !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
// 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符
if (!destDirName.endsWith(File.separator))
{
destDirName = destDirName + File.separator;
}
File destDir = new File(destDirName);
// 如果目标文件夹存在
if (destDir.exists())
{
// 如果允许覆盖则删除已存在的目标目录
if (overlay)
{
try
{
deleteDirectory(new File(destDirName));
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
MESSAGE = "Copy directory failed:destination directory "
+ destDirName + "Already exists !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
}
else
{
if (!destDir.mkdirs())
{
System.out.println("Copy directory failed:Create destination directory failed !");
return false;
}
}
boolean flag = true;
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++)
{
// 复制文件
if (files[i].isFile())
{
flag = copyFile(files[i].getAbsolutePath(), destDirName
+ files[i].getName(), overlay);
if (!flag)
break;
}
else if (files[i].isDirectory())
{
flag = copyDirectory(files[i].getAbsolutePath(), destDirName
+ files[i].getName(), overlay);
if (!flag)
break;
}
}
if (!flag)
{
MESSAGE = "copy directory" + srcDirName + "to" + destDirName
+ " fail !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
else
{
return true;
}
}
/**
* 物理删除悬浮菜单图片
* @param url
*/
public static void deleteImageFile(String url)
{
String rootUrl = XMLFactory.getValueString("publish.resourceHardiskPath");
StringBuffer generalFilePathSB = new StringBuffer();
generalFilePathSB.append(rootUrl);
generalFilePathSB.append(url);
String oldImagePath = generalFilePathSB.toString();
delOldResource(oldImagePath);
}
/**
* 检查海报真实尺寸 1.如果尺寸为空 或不存在,则默认取其真实尺寸; 2.有尺寸则校验尺寸大小,不匹配抛出错误
* @param file
* @param posterType
* @return
*/
public static boolean checkImageFileSize(File file, String posterType)
{
if (StringUtils.isEmpty(posterType))
{
return Boolean.TRUE;
}
BufferedImage image = null;
try
{
FileInputStream fis = new FileInputStream(file);
image = javax.imageio.ImageIO.read(fis);
}
catch (Exception e)
{
return Boolean.FALSE;
}
int height = image.getHeight();
int width = image.getWidth();
String realSpel = width + "*" + height;
if (posterType.indexOf(realSpel) != -1)
{
return Boolean.TRUE;
}
else
{
return Boolean.FALSE;
}
}
/**
* 取图片真实尺寸
* @param file
* @param posterType
* @return
*/
public static String getImageFileSize(File file)
{
BufferedImage image = null;
try
{
FileInputStream fis = new FileInputStream(file);
image = javax.imageio.ImageIO.read(fis);
}
catch (Exception e)
{
return null;
}
int height = image.getHeight();
int width = image.getWidth();
return width + "*" + height;
}
/**
* @param string
*/
public static boolean createDir(String dir)
{
boolean result = false;
File f = new File(toLocalDir(dir));
if (f.exists())
{
return true;
}
result = f.mkdir();
if (!result)
{
result = f.mkdirs();
}
return result;
}
public static String toLocalDir(String dir)
{
String osName = System.getProperty("os.name").toLowerCase();
return toLocalDir(osName, dir);
}
public static String toLocalDir(String osName, String dir)
{
osName = osName.toLowerCase();
if (osName.indexOf("windows") != -1)
{
return dir.replace('/', '\\');
}
return dir.replace('\\', '/');
}
/**
* Description : 镜像
*
* @param srcPath 来源文件
* @param dstPath 目标文件
* @throws Exception
*
*/
public static void mirror(File srcPath, File dstPath) throws Exception
{
mirrordelFile(srcPath, dstPath);
copyDirectory(srcPath, dstPath);
}
// 镜像 根据目标 删除 来源的文件
private static void mirrordelFile(File src, File dest)
{
if (!dest.exists())
{
return;
}
if (!src.exists())
{
if (dest.isDirectory())
{
delete(dest);
}
else
{
boolean flag = dest.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
return;
}
if (dest.isDirectory())
{
if (src.isFile())
{
boolean flag = dest.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
else
{
File[] chilefiles = dest.listFiles();
if (null != chilefiles && chilefiles.length > 0)
{
for (int i = 0; i < chilefiles.length; i++)
{
File dest2 = chilefiles[i];
String filename = dest2.getName();
String srcPath = src.getPath();
File src2 = new File(srcPath + File.separator
+ filename);
mirrordelFile(src2, dest2);
}
}
}
}
else
{
if (src.isDirectory())
{
boolean flag = dest.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
}
}
/**
* 目录复制
*
* @param srcPath 源目录
* @param dstPath 目标目录
* @throws IOException
*/
public static void copyDirectory(File srcPath, File dstPath)
throws Exception
{
if (srcPath.isDirectory())
{
if (!dstPath.exists())
{
boolean ismkSus = dstPath.mkdirs();
if (!ismkSus)
{
logger.excepFuncDebugLog("this directory is exists:" + dstPath);
}
}
String files[] = srcPath.list();
for (int i = 0; i < files.length; i++)
{
File ff = new File(dstPath, files[i]);
File srcff = new File(srcPath, files[i]);
copyDirectory(srcff, ff);
}
}
else
{
if (!srcPath.exists())
{
System.out.println("File or directory " + srcPath
+ "does not exist.");
}
else
{
copy(srcPath, dstPath);
}
}
}
private static void delete(File file)
{
if (file.isDirectory())
{
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
{
if (files[i].isDirectory())
{
delete(files[i]);
}
else
{
boolean flag = files[i].delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
}
boolean flag = file.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
else
{
boolean flag = file.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
}
/**
* Description : 保存图片到物理路径下
*
* @param src
* @param dst
* @throws Exception
*/
public static void copy(File src, File dst) throws Exception
{
InputStream srcIo = null;
try
{
long srctime = src.lastModified();
if (dst.exists())
{
long srcfilesize = src.length();
long dstfilesize = dst.length();
long dsttime = dst.lastModified();
if (srcfilesize == dstfilesize && srctime == dsttime)
{
return;
}
}
srcIo = new FileInputStream(src);
copyStream(srcIo, dst, src.length());
boolean flag = dst.setLastModified(srctime);
if (!flag)
{
logger.excepFuncDebugLog("copy file is failed");
}
}
catch (FileNotFoundException e)
{
StringBuilder msg = new StringBuilder(src.getAbsolutePath());
msg.append("The file does not exist !");
logger.excepFuncDebugLog(msg.toString());
throw e;
}
catch (IOException e)
{
StringBuilder msg = new StringBuilder(src.getAbsolutePath());
msg.append("copy to");
msg.append(dst.getAbsolutePath());
msg.append("File failed !");
logger.excepFuncDebugLog(msg.toString());
throw e;
}
finally
{
if (null != srcIo)
{
srcIo.close();
}
}
}
private static void copyStream(InputStream src, File dst,
final long byteCount) throws Exception
{
FileChannel srcChannel = null;
FileChannel dstChannel = null;
BufferedInputStream in = null;
OutputStream out = null;
FileOutputStream fOut = null;
try
{
if (!dst.exists())
{
boolean flag = dst.createNewFile();
if (!flag)
{
logger.excepFuncDebugLog("create file is failed");
}
}
if (src instanceof FileInputStream && byteCount > -1)
{
srcChannel = ((FileInputStream)src).getChannel();
fOut = new FileOutputStream(dst);
dstChannel = fOut.getChannel();
if (VIRTUAL_MEMORY_SIZE > byteCount)
{
srcChannel.transferTo(0, srcChannel.size(), dstChannel);
}
else
{
long postion = 0;
while (byteCount > postion)
{
long needCopyByte = byteCount - postion;
if (needCopyByte > VIRTUAL_MEMORY_SIZE)
{
needCopyByte = VIRTUAL_MEMORY_SIZE;
}
postion += srcChannel.transferTo(postion,
needCopyByte,
dstChannel);
}
}
}
else
{
in = new BufferedInputStream(src, BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("file copy failure");
throw e;
}
finally
{
try
{
if (null != dstChannel)
{
dstChannel.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("dstChannel close failure");
}
try
{
if (null != fOut)
{
fOut.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("fOut close failure");
}
try
{
if (null != srcChannel)
{
srcChannel.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("srcChannel close failure");
}
try
{
if (null != in)
{
in.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("in close failure");
}
try
{
if (null != out)
{
out.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("out close failure");
}
}
}
/**
* 得到图片文件的BufferedImage对象(用于获取图片的相关属性: 尺寸等)
* @param url
* @return
* @throws IOException
* @return BufferedImage
* @exception throws
*/
public static BufferedImage fileToImage(String url) throws IOException
{
File file = new File(url);
FileInputStream is = new FileInputStream(file);
BufferedImage sourceImg = javax.imageio.ImageIO.read(is);
return sourceImg;
}
}
FileMgrTools:
package com.xxx.dhm.portalMS.common.util;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import com.xxx.dhm.common.config.impl.XMLFactory;
/**
* ClassName:FileMgrTools
* 文件操作工具类,包括对文件夹和文件的操作
* @author
* @version
* @since Ver 1.1
* @Date
*/
public class FileMgrTools
{
public static final Logger logger = Logger.getLogger(FileMgrTools.class);
/**
* 删除文件夹
* @param path
* @return
* @throws Exception
*/
public static void deleteFile(File file)
{
if (file.exists())
{ // 判断文件是否存在
if (file.isFile())
{ // 判断是否是文件
boolean b = file.delete(); // delete()方法 你应该知道 是删除的意思;
if (b)
{
logger.debug("delete success...");
}
}
else if (file.isDirectory())
{ // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++)
{ // 遍历目录下所有的文件
deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
}
}
boolean b = file.delete();
if (b)
{
logger.debug("delete success...");
}
}
else
{
logger.debug("file not exist!");
}
}
/**
* 创建一个文件夹
* @param path
* @return
* @throws Exception
*/
public static boolean createFolder(String path) throws Exception
{
File dirFile = null;
boolean isCreate = true;
try
{
logger.debug("create file folder...");
dirFile = new File(path);
// 判断文件夹是否已存在
boolean isExist = dirFile.exists();
if (!isExist)
{
// 文件夹不存在,则创建一个
isCreate = dirFile.mkdirs();
}
}
catch (Exception e)
{
throw e;
}
return isCreate;
}
/*
* 删除一个文件夹
* @param path
* @return
* @throws Exception
*
public static boolean deleteFolder(String path) throws Exception{
try{
logger.debug("删除文件夹...");
}catch(Exception e){
throw e;
}
return true;
}
*/
/**
* 从磁盘查找文件是否存在
* @param path
* @param fileName
* @return true:存在 false:不存在
* @throws Exception
*/
public static boolean isFileExists(String path, String fileName) throws Exception
{
boolean isExists = false;
File file = null;
try
{
logger.debug("Query file exists ...");
if (fileName == null || "".equalsIgnoreCase(fileName))
{
file = new File(path);
}
else
{
file = new File(path + "/" + fileName);
}
if (file.exists())
{
// 存在返回true
isExists = true;
}
}
catch (Exception e)
{
throw e;
}
return isExists;
}
/**
* 从磁盘读取文件内容
* @param path
* @param fileName
* @return 文件内容(String)
* @throws Exception
*/
public static String getFileContent(String path, String fileName) throws Exception
{
String content = "";
FileInputStream inFile = null;
List<byte[]> bytesList = null;
int byteSize = 0;
try
{
logger.debug("Read the file contents from the disk ...");
// 判断文件是否存在
if (isFileExists(path, fileName))
{
bytesList = new ArrayList<byte[]>();
// 新建文件读取流对象
File in = new File(path + "/" + fileName);
inFile = new FileInputStream(in);
byte[] buffer = new byte[1024];
int i = 0;
logger.debug("Loop to read 1024 bytes ...");
// 循环读取1024字节到bytesList中
while ((i = inFile.read(buffer)) != -1)
{
// byteSize用于保存总字节大小
byteSize += i;
byte[] temp = new byte[i];
// 将读取到的实际大小存入temp中
System.arraycopy(buffer, 0, temp, 0, i);
bytesList.add(temp);
}
// 申请一个总大小的字节空间
byte[] total = new byte[byteSize];
int pos = 0;
logger.debug("Will read the content is stored in a variable ...");
// 将bytesList中内容取出入到总的字节空间中
for (int j = 0; j < bytesList.size(); j++)
{
byte[] temp = bytesList.get(j);
// 将每个临时字节数据存入一个总的字节变量中
System.arraycopy(temp, 0, total, pos, temp.length);
pos += temp.length;
}
String fileEncoding = XMLFactory.getValueString("plugin.staticPage.charSet");
// 按UTF-8编码方式将字节数据转换成字符数据
content = new String(total, fileEncoding);
// content = new
// String(content.getBytes(fileEncoding),Constants.PAGE_ENCODING.getStringValue());
// File f = new File(path + "/" + fileName);
// read = new InputStreamReader(new FileInputStream(f),"UTF-8");
// BufferedReader reader=new BufferedReader(read);
// String line;
// while ((line = reader.readLine()) != null) {
// content += line;
// }
}
}
catch (Exception e)
{
throw e;
}
finally
{
// 关闭打开的文件流
if (inFile != null)
{
inFile.close();
inFile = null;
}
}
return content;
}
/**
* 根据文件内容创建一个磁盘文件
* @param path
* @param fileName
* @param content
* @return
* @throws Exception
*/
public static boolean createFileByContent(String path, String fileName, byte[] content) throws Exception
{
createFolder(path);
DataOutputStream out = null;
File file = null;
boolean isCreate = true;
try
{
logger.debug("Create a disk file according to the content ...");
// 新建一个文件句柄
file = new File(path + "/" + fileName);
// 如果文件已存在则先删除
if (file.exists())
{
// 如果删除失败,控制下面不再写文件
isCreate = file.delete();
}
else
{
// 文件不存在则创建一个空文件,如果创建失败,控制下面不再写文件
isCreate = file.createNewFile();
}
// 如果删除或创建文件成功,则写入文件内容
if (isCreate)
{
// 新建一个文件输入流对象
out = new DataOutputStream(new FileOutputStream(file));
// 将内容写入创建的文件中
out.write(content);
}
}
catch (Exception e)
{
throw e;
}
finally
{
// 关闭创建的文件流
if (out != null)
{
out.close();
out = null;
}
}
return isCreate;
}
/**
* 根据源和目的复制一个文件
* @param orgPath
* @param orgFileName
* @param destPath
* @param destFileName
* @return
* @throws Exception
*/
public static boolean copyFile(String orgPath, String orgFileName, String destPath, String destFileName)
throws Exception
{
FileInputStream inFile = null;
FileOutputStream outFile = null;
boolean isCopy = true;
String org = null;
String dest = null;
try
{
// 判断源文件是否存在
if (isFileExists(orgPath, orgFileName))
{
// 新建源和目标文件句柄
if (orgFileName == null || orgFileName.equalsIgnoreCase(""))
{
org = orgPath;
}
else
{
org = orgPath + "/" + orgFileName;
}
if (destFileName == null || destFileName.equalsIgnoreCase(""))
{
dest = destPath;
}
else
{
dest = destPath + "/" + destFileName;
}
File orgFile = new File(org);
File destFile = new File(dest);
//创建目录
File destDir = new File(destPath);
if (!destDir.exists())
{
boolean flag = destDir.mkdirs();
if (flag)
{
logger.debug("this directory is created successful...");
}
}
if (destFile.exists())
{
// 如果删除失败,控制下面不再复制文件
isCopy = destFile.delete();
}
if (isCopy)
{
// 创建源和目标文件的流对象
inFile = new FileInputStream(orgFile);
outFile = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int i = 0;
// 从源文件中每次读取1024字节存入目标文件
while ((i = inFile.read(buffer)) != -1)
{
outFile.write(buffer, 0, i);
}
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
closeStream(inFile, outFile);
}
return isCopy;
}
private static void closeStream(FileInputStream inFile, FileOutputStream outFile)
{
// 关闭目标文件流对象
if (outFile != null)
{
try
{
outFile.close();
}
catch (Exception e)
{
outFile = null;
}
}
// 关闭源文件流对象
if (inFile != null)
{
try
{
inFile.close();
}
catch (Exception e)
{
inFile = null;
}
}
}
/*
* 删除一个文件
* @param path
* @param fileName
* @return
* @throws Exception
*
public static boolean deleteFile(String path, String fileName) throws Exception{
try{
logger.debug("删除一个文件...");
}catch(Exception e){
throw e;
}
return true;
}
*/
/**
* 文件夹镜象对拷
* @param orgPath 源文件夹路径
* @param destPath 目标文件夹路径
* @param copySubFolder 是否拷贝子文件件
* @return
* @throws Exception
*/
public static boolean folderCopy(String orgPath, String destPath, boolean copySubFolder) throws Exception
{
boolean isCopy = true;
try
{
if (isFileExists(orgPath, null))
{
logger.debug("The folder image copy ...");
// 创建目标文件夹
createFolder(destPath);
// 获取源文件夹的文件列表
File[] fileList = getFolderFilesList(orgPath);
if (fileList != null && fileList.length > 0)
{
logger.debug("Copy the file to the target folder ...");
// 一个一个复制文件到目标文件夹
for (int i = 0; i < fileList.length; i++)
{
// 调用复制方法完成文件的复制功能
isCopy = copyFile(orgPath, fileList[i].getName(), destPath, fileList[i].getName());
// 如果有一个文件复制失败,则整个复制失败
if (!isCopy)
{
break;
}
}
}
}
}
catch (Exception e)
{
throw e;
}
return isCopy;
}
/**
* 文件夹镜象对拷-根据过滤条件
* @param orgPath 源文件夹路径
* @param destPath 目标文件夹路径
* @param copySubFolder 是否拷贝子文件件
* @return
* @throws Exception
*/
public static boolean folderCopyByFileFilter(String orgPath, String destPath, FileFilter fileFilter)
throws Exception
{
boolean isCopy = true;
try
{
if (isFileExists(orgPath, null))
{
// 拷贝当前目录下的文件
folderCopy(orgPath, destPath, false);
// 拷贝当前目录下未被fileFilter过滤的子文件夹文件
File[] subFolderList = getSubFolderList(orgPath, fileFilter);
if (subFolderList != null && subFolderList.length > 0)
{
String folderName = null;
String subOrgPath = null;
String subDestPath = null;
for (int j = 0; j < subFolderList.length; j++)
{
if (subFolderList[j].isDirectory())
{
folderName = subFolderList[j].getName();
subOrgPath = orgPath + "/" + folderName;
subDestPath = destPath + "/" + folderName;
// 子文件件拷贝(嵌套)
isCopy = folderCopyByFileFilter(subOrgPath, subDestPath, fileFilter);
if (!isCopy)
{
break;
}
}
}
}
}
}
catch (Exception e)
{
throw e;
}
return isCopy;
}
/**
* 获取文件夹下子文件夹列表-根据过滤条件
* @param path
* @return
* @throws Exception
*/
private static File[] getSubFolderList(final String path, FileFilter fileFilter) throws Exception
{
File[] fileList = null;
try
{
logger.debug("Suddenly get folder folder list -According to the filtering conditions ...");
if (path != null && !"".equalsIgnoreCase(path))
{
// 创建一个文件句柄
File dir = new File(path);
// 读取文件列表
fileList = dir.listFiles(fileFilter);
// 文件列表排序
if (fileList != null && fileList.length > 0)
{
Arrays.sort(fileList);
}
}
}
catch (Exception e)
{
throw e;
}
return fileList;
}
/**
* 获取文件夹下文件列表
* @param path
* @return
* @throws Exception
*/
private static File[] getFolderFilesList(final String path) throws Exception
{
File[] fileList = null;
try
{
logger.debug("Gets the file folder list ...");
// 创建一个内部类实现文件夹过滤,只罗列文件,不罗列文件夹
FileFilter filter = new FileFilter()
{
public boolean accept(File pathname)
{
boolean isAccept = false;
// 过滤文件夹和以__.为名的临时生成的文件
if (pathname.isFile())
{
String fileName = pathname.getName();
if (fileName != null && fileName.indexOf("__.") < 0)
{
isAccept = true;
}
}
return isAccept;
}
};
if (path != null && !"".equalsIgnoreCase(path))
{
// 创建一个文件句柄
File dir = new File(path);
// 读取文件列表
fileList = dir.listFiles(filter);
// 文件列表排序
if (fileList != null && fileList.length > 0)
{
Arrays.sort(fileList);
}
}
}
catch (Exception e)
{
throw e;
}
return fileList;
}
public static String getRootPath(String curretpath, boolean isFile)
{
if (null == curretpath || "".equals(curretpath))
{
return curretpath;
}
File f = new File(curretpath);
curretpath = f.getPath();
int tmp = 0;
StringBuffer buf = new StringBuffer();
while ((tmp = curretpath.indexOf("/", tmp)) != -1)
{
tmp++;
if (isFile)
{
isFile = false;
continue;
}
buf.append("..").append("/");
}
return buf.toString().equals("") ? "" : buf.toString().substring(0, buf.length() - 1);
}
}
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ include file="../common/language.jsp" %>
<%
String contextPath = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><s:text name="msg.portalMS.channelMgr.assignChannelLenovo" /></title>
<link href="../style/base<%=language_css%>.css" rel="stylesheet" type="text/css" />
<link href="../style/ext-all.css" rel="stylesheet" type="text/css" />
<%@ include file="../common/commonJS.jsp" %>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/dialogShow.js"></script>
<script type="text/javascript" src="../js/validateform.js"></script>
<script type="text/javascript">
function showList(event,day)
{
document.getElementById("tabPageId").value = day;
//归属地
var cityId = $("#cityId").val();
if(day==1){
var tli = document.getElementById("tab_nav").getElementsByTagName("li");
tli[0].className="draw_on";
tli[1].className="";
var resourceId = document.getElementById("hid").value;
var url = "<%=request.getContextPath()%>/channel/findAssignOrNoAssignLenovo.action"
+ "?channel.resourceId="+resourceId
+ "&channel.cityId=" + cityId
+ "&action=association";
mainAssetTypeFrame.location.href= url;
return false;
}
else if(day==2){
var tli = document.getElementById("tab_nav").getElementsByTagName("li");
tli[0].className="";
tli[1].className="draw_on";
var resourceId = document.getElementById("hid").value;
var url = "<%=request.getContextPath()%>/channel/findAssignOrNoAssignLenovo.action"
+ "?channel.resourceId="+resourceId
+ "&channel.cityId=" + cityId
+ "&action=noassociation";
mainAssetTypeFrame.location.href= url;
return false;
}
return false;
}
function showList1(day)
{
var tli = document.getElementById("tab_nav").getElementsByTagName("li");
tli[0].className="draw_on";
tli[1].className="";
//document.getElementById("assetTypeDiv").style.display="none";
document.getElementById("tabPageId").value = "1";
var resourceId = document.getElementById("hid").value;
var cityId = $("#cityId").val();
var url = "<%=request.getContextPath()%>/channel/findAssignOrNoAssignLenovo.action?channel.resourceId=" + resourceId
+ "&channel.cityId=" + cityId
+ "&action=association";
mainAssetTypeFrame.location.href = url;
}
</script>
</head>
<body οnlοad="showList1(1)">
<form id="typeTree" name="typeTree" action="" method="post">
<input id="assetTypeId" type="hidden" name="assetTypeId" />
<input id="tabPageId" type="hidden" name="tabPageId" />
<input id="cityId" type="hidden" name="channel.cityId" value="<s:property value="channel.cityId"/>"/>
<div id="top_blank"></div>
<!---导航 --->
<div class="r_nav">
<div class="left"><img src="../images/nav_l.gif" width="5"
height="29" /></div>
<div class="ct"><s:text name="msg.portalMS.channelTypemgr.current.position" />
<s:text name="msg.portalMS.businessmanagement.name" /> ><s:text name="msg.portalMS.channelMgr.name" /> > <s:text name="msg.portalMS.channelMgr.assignChannelLenovo" /></div>
<div class="right"><img src="../images/nav_r.jpg" width="5"
height="29" /></div>
</div>
<div class="tab_main">
<div id="tab_switchdraw">
<s:hidden id="hid" name="channel.resourceId" />
<ul id="tab_nav">
<li οnclick="showList(event,1)" class="draw_on">
<s:text name="msg.portalMS.channelMgr.assignChannelLenovo.result" />
</li>
<li οnclick="showList(event,2)" ><s:text name="msg.portalMS.channelMgr.assignChannelLenovo.hand" />
</li>
</ul>
</div>
</div>
<div id="cdata_list" style="margin-left: 5px">
<iframe src=""
name="mainAssetTypeFrame" width="100%"
frameborder="0" id="mainAssetTypeFrame" title="mainAssetTypeFrame" scrolling="no" />
</div>
</form>
</body>
</html>
<resourceHardiskPath>/usr/local/portalMS/jboss5/server/default/deploy/portal.war/</resourceHardiskPath>
/**
* 设置频道文件名全路径
*
* @param fileName
* 页面请求的文件名
* @param index
* 资源序号
* @return
*/
private String setFilePath(String fileName, String index) //fileName:part.jpg index:0
{
// 从配置文件读取根路径
String rootUrl = XMLFactory.getValueString("publish.resourceHardiskPath");
StringBuffer filePathSB = new StringBuffer();
filePathSB.append(rootUrl);
filePathSB.append(File.separator);
filePathSB.append(Constants.IEPG_LOGO_PATH.getStringValue());
filePathSB.append(File.separator);
// 频道文件名
filePathSB.append(fileName.substring(0, fileName.lastIndexOf(".")));
filePathSB.append("_");
filePathSB.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString());
filePathSB.append(index);
filePathSB.append(fileName.substring(fileName.lastIndexOf(".")));
// 频道文件名全路径
return filePathSB.toString();
// /usr/local/portalMS/jboss5/server/default/deploy/portal.war/\logo\part_201402201451080.jpg
}
resources.get(i) =[D:\tomcat_portal\work\Catalina\localhost\portalMS\upload__26cdfb2f_1444df1297a__8000_00000008.tmp]
filePath:/usr/local/portalMS/jboss5/server/default/deploy/portal.war/\logo\part_201402201451080.jpg
FileUtil.uploadResource(resources.get(i), filePath, true);
FileUtil:
package com.xxxxxx.dhm.portalMS.common.util;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.Enumeration;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import com.xxxxxx.dhm.common.config.impl.XMLFactory;
import com.xxxxxx.dhm.portalMS.common.Constants;
import com.xxxxxx.dhm.portalMS.common.DebugLogHelper;
import com.xxxxxx.dhm.portalMS.common.SerConstants;
import com.xxxxxx.dhm.portalMS.exception.PortalMSException;
/**
* FileUtil.java 文件操作工具类
*
* @author kanxiaohui
*/
public class FileUtil
{
private static final DebugLogHelper logger = new DebugLogHelper(FileUtil.class);
private static String MESSAGE = "";
public static final char separator = '\\';
public static final char linux_separator = '/';
private static final int BUFFER_SIZE = 16 * 1024;
private static final long VIRTUAL_MEMORY_SIZE = 512 * 1024 * 1024;
/**
* 读取文件的内容(文件的格式仅限.html、.css、.js)
* @param filePath
* @return
* @throws IEPGMException
* @return String
* @throws Exception
* @exception throws
*/
public static String readFileContent(String filePath, String encode)
throws Exception
{
BufferedInputStream bis = null;
StringBuffer sb = new StringBuffer();
try
{
bis = new BufferedInputStream(new FileInputStream(
new File(filePath)));
byte[] buf = new byte[1024 * 10];
int len = -1;
while ((len = bis.read(buf)) != -1)
{
sb.append(new String(buf, 0, len, encode));
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("read file content error. reason:" + e);
throw new IOException(e);
}
finally
{
try
{
bis.close();
}
catch (Exception e)
{
logger.excepFuncDebugLog("read file content error. reason:" + e);
throw new Exception(e);
}
}
return sb.toString();
}
/**
* 内容输出到文件
* @param content 内容
* @param filePath 文件路径
* @param encode 编码
* @throws Exception
* @return void
* @exception throws
*/
public static void stringWriteToFile(String content, String filePath,
String encode) throws Exception
{
File indexTemplateFile = new File(filePath);
if (indexTemplateFile.exists())
{
boolean flag = indexTemplateFile.delete();
if (!flag)
{
logger.excepFuncDebugLog("delete file is failed");
}
}
try
{
indexTemplateFile.createNewFile();
}
catch (IOException e1)
{
logger.excepFuncDebugLog("creat file is failed. filePath = " + filePath);
throw e1;
}
BufferedOutputStream out = null;
try
{
out = new BufferedOutputStream(new FileOutputStream(
indexTemplateFile));
out.write(content.getBytes(encode));
}
catch (Exception e)
{
logger.excepFuncDebugLog("The content is written to the file failed. filePath = "
+ filePath);
throw e;
}
finally
{
try
{
out.close();
}
catch (Exception e)
{
logger.excepFuncDebugLog("Closes the output stream failure . ");
throw (e);
}
}
}
/**
* 保存文件输入流到指定目录和文件名的文件实体中
*
* @param destFileName 目标文件名
* @param in 源文件输入流
* @param destFilePath 目标文件路径
* @throws Exception
*/
public static void saveFile(String destFileName, InputStream in,
String destFilePath) throws IOException
{
OutputStream bos = null;// 建立一个保存文件的输出流
try
{
destFilePath = trimFilePath(destFilePath) + "/" + destFileName;
bos = new FileOutputStream(destFilePath, false);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1)
{
bos.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (bos != null)
{
bos.close();
}
if (in != null)
{
in.close();
}
}
}
/**
* 保存文件
*
* @param destFile 目标文件完整路径
* @param in 源文件输入流
* @throws Exception
*/
public static void saveFile(File destFile, InputStream in)
throws IOException
{
OutputStream bos = null;
try
{
bos = new FileOutputStream(destFile, false);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1)
{
bos.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (bos != null)
{
bos.close();
}
if (in != null)
{
in.close();
}
}
}
/**
* zip文件解压缩
*
* @param zipFileName 文件完整路径
* @param outputDirectory 解压保存路径
* @param isCover 是否重名覆盖
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static void unzip(String zipFileName, String outputDirectory,
boolean isCover) throws IOException
{
logger.excepFuncDebugLog("To extract the files :" + zipFileName
+ SerConstants.COLON + outputDirectory);
ZipFile zipFile = new ZipFile(zipFileName);
try
{
Enumeration<ZipEntry> e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
InputStream in = null;
FileOutputStream out = null;
while (e.hasMoreElements())
{
zipEntry = e.nextElement();
if (zipEntry.isDirectory())
{
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
if (!f.exists())
{
if (!f.mkdirs())
{
zipFile.close();
throw new IOException(
"Failed to create the directory!");
}
}
}
else
{
String fileName = zipEntry.getName();
fileName = fileName.replace(separator, File.separatorChar);
fileName = fileName.replace(linux_separator,
File.separatorChar);
if (fileName.indexOf(File.separatorChar) != -1)
{
createDirectory(outputDirectory, getPath(fileName));
fileName = fileName.substring(fileName.lastIndexOf(separator) + 1,
fileName.length());
}
File f = new File(outputDirectory + File.separator
+ zipEntry.getName());
if (f.exists())
{
if (isCover)
{
// 如果要覆盖,先删除原有文件
FileUtils.delete(f);
}
else
{
// 如果不覆盖,不做处理
continue;
}
// continue;
}
if (!f.createNewFile())
{
zipFile.close();
throw new IOException("Creating file failed !");
}
try
{
in = zipFile.getInputStream(zipEntry);
out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1)
{
out.write(by, 0, c);
}
}
catch (IOException ex)
{
throw ex;
}
finally
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
}
}
}
catch (IOException e)
{
throw e;
}
finally
{
zipFile.close();
}
}
@SuppressWarnings("unchecked")
public static void unzipNoDir(String zipFileName, String outputDirectory,
boolean isCover) throws IOException
{
logger.excepFuncDebugLog("To extract the files :" + zipFileName
+ SerConstants.COLON + outputDirectory);
ZipFile zipFile = new ZipFile(zipFileName);
try
{
Enumeration<ZipEntry> e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
InputStream in = null;
FileOutputStream out = null;
while (e.hasMoreElements())
{
zipEntry = e.nextElement();
if (zipEntry.isDirectory())
{
}
else
{
// String fileName = zipEntry.getName();
String newName = zipEntry.getName()
.substring(zipEntry.getName().lastIndexOf('/') + 1,
zipEntry.getName().length());
File f = new File(outputDirectory + File.separator
+ newName);
if (f.exists())
{
if (isCover)
{
// 如果要覆盖,先删除原有文件
FileUtils.delete(f);
}
else
{
// 如果不覆盖,不做处理
continue;
}
}
if (!f.createNewFile())
{
zipFile.close();
throw new IOException("Creating file failed !");
}
try
{
in = zipFile.getInputStream(zipEntry);
out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1)
{
out.write(by, 0, c);
}
}
catch (IOException ex)
{
throw ex;
}
finally
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
}
}
}
catch (IOException e)
{
throw e;
}
finally
{
zipFile.close();
}
}
public static String trimFilePath(String filePath)
{
if (filePath == null || filePath.trim().length() == 0)
{
return "";
}
if (filePath.endsWith(String.valueOf(separator)))
{
filePath = filePath.substring(0, filePath.length() - 1);
}
return filePath;
}
private static void createDirectory(String directory, String subDirectory)
throws IOException
{
String dir[];
File fl = new File(directory);
if (subDirectory.equals("") && fl.exists() != true)
{
if (fl.mkdirs())
{
throw new IOException("Creating file failed !" + directory);
}
}
else if (!subDirectory.equals(""))
{
dir = subDirectory.replace(separator, File.separatorChar)
.split("\\\\");
StringBuffer sBuffer = new StringBuffer(directory);
for (int i = 0; i < dir.length; i++)
{
File subFile = new File(sBuffer.toString() + File.separator
+ dir[i]);
if (!subFile.exists())
{
if (!subFile.mkdirs())
{
throw new IOException("Creating file failed !"
+ subDirectory);
}
}
sBuffer.append(separator + dir[i]);
}
}
}
/**
* 当文件路径包含文件名时,截取该文件所在文件夹路径
*
* @param fileName
* @return
*/
public static String getPath(String fileName)
{
if (fileName.lastIndexOf(File.separator) >= 0)
{
return fileName.substring(0, fileName.lastIndexOf(File.separator));
}
return fileName;
}
/**
* 把字符串写入指定文件
*
* @param fileName
* @param content
*/
public static void writeStringToFile(String fileName, String content)
throws IOException
{
File file = new File(fileName);
if (file.exists())
{
FileUtils.delete(file);
}
// if (file.createNewFile()) {
// throw new IOException("创建文件:" + fileName + "失败!");
// }
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.close();
}
/**
* 获取某文件路径的跟路径
*
* @param fileName
* @return
*/
public static String getRootPath(String fileName)
{
if (fileName.lastIndexOf("/") >= 0)
{
return "/" + fileName.split("/")[1];
}
return fileName;
}
/**
* 删除指定的文件
* @param file
*/
public static void deleteFile(File file) throws IOException
{
if (file == null || !file.exists())
{
return;
}
if (file.isDirectory())
{
deleteDirectory(file);
}
else
{
if (!file.delete())
{
logger.excepFuncDebugLog("deleteFile Delete file failed :"
+ file.getAbsolutePath());
}
}
}
/**
* 删除指定的目录
* @param directory
* @throws IOException
*/
public static void deleteDirectory(File directory) throws IOException
{
String[] subFiles = directory.list();
for (int i = 0; i < subFiles.length; i++)
{
File subFile = new File(directory.getAbsolutePath()
+ File.separator + subFiles[i]);
deleteFile(subFile);
}
if (!directory.delete())
{
logger.excepFuncDebugLog("deleteDirectory Delete the specified directory failed :"
+ directory.getAbsolutePath());
}
}
/**
* 获取旧图片全路径
* @param filePath 图片的路径
* @param imageUrl 数据库中保存的图片路径
* @return
*/
public static String getOldResourcePath(String filePath, String imageUrl)
{
int imageIndex = 0;
int imageIndex2 = 0;
int pathIndex = 0;
int pathIndex2 = 0;
if (imageUrl != null && !imageUrl.equals(""))
{
imageIndex = imageUrl.lastIndexOf("\\");
imageIndex2 = imageUrl.lastIndexOf("/");
imageIndex = (imageIndex > imageIndex2 ? imageIndex : imageIndex2);
}
if (filePath != null && !filePath.equals(""))
{
pathIndex = filePath.lastIndexOf("\\");
pathIndex2 = filePath.lastIndexOf("/");
pathIndex = (pathIndex > pathIndex2 ? pathIndex : pathIndex2);
}
StringBuffer oldImagePath = new StringBuffer();
if (pathIndex > 0)
{
oldImagePath.append(filePath.substring(0, pathIndex));
}
else
{
oldImagePath.append(filePath);
}
oldImagePath.append(File.separator);
if (imageIndex > 0)
{
oldImagePath.append(imageUrl.substring(imageIndex + 1));
}
else
{
oldImagePath.append(imageUrl);
}
return oldImagePath.toString();
}
/**
* 删除旧图片
* @param fullFilePath 删除图片的全路径
*/
public static void delOldResource(String fullFilePath)
{
if (fullFilePath != null && !fullFilePath.equals(""))
{
File outFile = new File(fullFilePath);
if (outFile.exists())
{
if (!outFile.delete())
{
logger.excepFuncDebugLog("delOldResource Remove a resource file failed :"
+ fullFilePath);
}
}
}
}
/**
* 资源上传的处理方法
* @param file 上传的文件实体
* @param cover 是否重名覆盖 true -- 是,false -- 否
* @throws PortalMSException
*/
public static void uploadResource(File file, String path, Boolean cover)
throws PortalMSException
{
if (file == null || path == null || path.equals(""))
{
return;
}
File outFile = null;
try
{
outFile = new File(path);
String pathName = FileUtil.getPath(outFile.getPath());
FileMgrTools.createFolder(pathName);
// 如果有同名文件
if (outFile.exists())
{
// 如果选择同名覆盖
if (cover)
{
org.apache.commons.io.FileUtils.forceDelete(outFile);
}
else
{// 否则退出操作
return;
}
}
else
{
if (!outFile.createNewFile())
{
throw new PortalMSException(
Constants.ERROR_CODE_NODE_RESOURCE_FIND.getLongValue(),
new IOException("Creating file failed !"));
}
}
// 创建源文件输入流
FileInputStream in = new FileInputStream(file);
// 保存输入流到指定文件路径
FileUtil.saveFile(outFile, in);
}
catch (Exception e)
{
e.printStackTrace();
throw new PortalMSException(
Constants.ERROR_CODE_NODE_RESOURCE_UPLOAD.getLongValue(), e);
}
}
/**
* 复制单个文件
*
* @param srcFileName 待复制的文件名
* @param descFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName,
boolean overlay)
{
File srcFile = new File(srcFileName);
// 判断源文件是否存在
if (!srcFile.exists())
{
MESSAGE = "source file:" + srcFileName + "not exist!";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
else if (!srcFile.isFile())
{
MESSAGE = "Copy file failed ,source file:" + srcFileName
+ "Is not a file !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
// 判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists())
{
// 如果目标文件存在并允许覆盖
if (overlay)
{
// 删除已经存在的目标文件,无论目标文件是目录还是单个文件
boolean b = new File(destFileName).delete();
if (b)
{
logger.excepFuncDebugLog("Successfully deleted ...");
}
}
}
else
{
// 如果目标文件所在目录不存在,则创建目录
if (!destFile.getParentFile().exists())
{
// 目标文件所在目录不存在
if (!destFile.getParentFile().mkdirs())
{
// 复制文件失败:创建目标文件所在目录失败
return false;
}
}
}
// 复制文件
int byteread = 0; // 读取的字节数
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
while ((byteread = in.read(buffer)) != -1)
{
out.write(buffer, 0, byteread);
}
return true;
}
catch (FileNotFoundException e)
{
return false;
}
catch (IOException e)
{
return false;
}
finally
{
try
{
if (out != null)
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
if (in != null)
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 复制整个目录的内容
*
* @param srcDirName 待复制目录的目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName,
boolean overlay)
{
// 判断源目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists())
{
MESSAGE = "Copy directory failed :source directory" + srcDirName
+ "no exist!";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
else if (!srcDir.isDirectory())
{
MESSAGE = "Copy directory failed :" + srcDirName
+ "Is not a directory !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
// 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符
if (!destDirName.endsWith(File.separator))
{
destDirName = destDirName + File.separator;
}
File destDir = new File(destDirName);
// 如果目标文件夹存在
if (destDir.exists())
{
// 如果允许覆盖则删除已存在的目标目录
if (overlay)
{
try
{
deleteDirectory(new File(destDirName));
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
MESSAGE = "Copy directory failed:destination directory "
+ destDirName + "Already exists !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
}
else
{
if (!destDir.mkdirs())
{
System.out.println("Copy directory failed:Create destination directory failed !");
return false;
}
}
boolean flag = true;
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++)
{
// 复制文件
if (files[i].isFile())
{
flag = copyFile(files[i].getAbsolutePath(), destDirName
+ files[i].getName(), overlay);
if (!flag)
break;
}
else if (files[i].isDirectory())
{
flag = copyDirectory(files[i].getAbsolutePath(), destDirName
+ files[i].getName(), overlay);
if (!flag)
break;
}
}
if (!flag)
{
MESSAGE = "copy directory" + srcDirName + "to" + destDirName
+ " fail !";
logger.excepFuncDebugLog(MESSAGE);
return false;
}
else
{
return true;
}
}
/**
* 物理删除悬浮菜单图片
* @param url
*/
public static void deleteImageFile(String url)
{
String rootUrl = XMLFactory.getValueString("publish.resourceHardiskPath");
StringBuffer generalFilePathSB = new StringBuffer();
generalFilePathSB.append(rootUrl);
generalFilePathSB.append(url);
String oldImagePath = generalFilePathSB.toString();
delOldResource(oldImagePath);
}
/**
* 检查海报真实尺寸 1.如果尺寸为空 或不存在,则默认取其真实尺寸; 2.有尺寸则校验尺寸大小,不匹配抛出错误
* @param file
* @param posterType
* @return
*/
public static boolean checkImageFileSize(File file, String posterType)
{
if (StringUtils.isEmpty(posterType))
{
return Boolean.TRUE;
}
BufferedImage image = null;
try
{
FileInputStream fis = new FileInputStream(file);
image = javax.imageio.ImageIO.read(fis);
}
catch (Exception e)
{
return Boolean.FALSE;
}
int height = image.getHeight();
int width = image.getWidth();
String realSpel = width + "*" + height;
if (posterType.indexOf(realSpel) != -1)
{
return Boolean.TRUE;
}
else
{
return Boolean.FALSE;
}
}
/**
* 取图片真实尺寸
* @param file
* @param posterType
* @return
*/
public static String getImageFileSize(File file)
{
BufferedImage image = null;
try
{
FileInputStream fis = new FileInputStream(file);
image = javax.imageio.ImageIO.read(fis);
}
catch (Exception e)
{
return null;
}
int height = image.getHeight();
int width = image.getWidth();
return width + "*" + height;
}
/**
* @param string
*/
public static boolean createDir(String dir)
{
boolean result = false;
File f = new File(toLocalDir(dir));
if (f.exists())
{
return true;
}
result = f.mkdir();
if (!result)
{
result = f.mkdirs();
}
return result;
}
public static String toLocalDir(String dir)
{
String osName = System.getProperty("os.name").toLowerCase();
return toLocalDir(osName, dir);
}
public static String toLocalDir(String osName, String dir)
{
osName = osName.toLowerCase();
if (osName.indexOf("windows") != -1)
{
return dir.replace('/', '\\');
}
return dir.replace('\\', '/');
}
/**
* Description : 镜像
*
* @param srcPath 来源文件
* @param dstPath 目标文件
* @throws Exception
*
*/
public static void mirror(File srcPath, File dstPath) throws Exception
{
mirrordelFile(srcPath, dstPath);
copyDirectory(srcPath, dstPath);
}
// 镜像 根据目标 删除 来源的文件
private static void mirrordelFile(File src, File dest)
{
if (!dest.exists())
{
return;
}
if (!src.exists())
{
if (dest.isDirectory())
{
delete(dest);
}
else
{
boolean flag = dest.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
return;
}
if (dest.isDirectory())
{
if (src.isFile())
{
boolean flag = dest.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
else
{
File[] chilefiles = dest.listFiles();
if (null != chilefiles && chilefiles.length > 0)
{
for (int i = 0; i < chilefiles.length; i++)
{
File dest2 = chilefiles[i];
String filename = dest2.getName();
String srcPath = src.getPath();
File src2 = new File(srcPath + File.separator
+ filename);
mirrordelFile(src2, dest2);
}
}
}
}
else
{
if (src.isDirectory())
{
boolean flag = dest.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
}
}
/**
* 目录复制
*
* @param srcPath 源目录
* @param dstPath 目标目录
* @throws IOException
*/
public static void copyDirectory(File srcPath, File dstPath)
throws Exception
{
if (srcPath.isDirectory())
{
if (!dstPath.exists())
{
boolean ismkSus = dstPath.mkdirs();
if (!ismkSus)
{
logger.excepFuncDebugLog("this directory is exists:" + dstPath);
}
}
String files[] = srcPath.list();
for (int i = 0; i < files.length; i++)
{
File ff = new File(dstPath, files[i]);
File srcff = new File(srcPath, files[i]);
copyDirectory(srcff, ff);
}
}
else
{
if (!srcPath.exists())
{
System.out.println("File or directory " + srcPath
+ "does not exist.");
}
else
{
copy(srcPath, dstPath);
}
}
}
private static void delete(File file)
{
if (file.isDirectory())
{
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
{
if (files[i].isDirectory())
{
delete(files[i]);
}
else
{
boolean flag = files[i].delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
}
boolean flag = file.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
else
{
boolean flag = file.delete();
if (!flag)
{
logger.excepFuncDebugLog("this file delete is failed");
}
}
}
/**
* Description : 保存图片到物理路径下
*
* @param src
* @param dst
* @throws Exception
*/
public static void copy(File src, File dst) throws Exception
{
InputStream srcIo = null;
try
{
long srctime = src.lastModified();
if (dst.exists())
{
long srcfilesize = src.length();
long dstfilesize = dst.length();
long dsttime = dst.lastModified();
if (srcfilesize == dstfilesize && srctime == dsttime)
{
return;
}
}
srcIo = new FileInputStream(src);
copyStream(srcIo, dst, src.length());
boolean flag = dst.setLastModified(srctime);
if (!flag)
{
logger.excepFuncDebugLog("copy file is failed");
}
}
catch (FileNotFoundException e)
{
StringBuilder msg = new StringBuilder(src.getAbsolutePath());
msg.append("The file does not exist !");
logger.excepFuncDebugLog(msg.toString());
throw e;
}
catch (IOException e)
{
StringBuilder msg = new StringBuilder(src.getAbsolutePath());
msg.append("copy to");
msg.append(dst.getAbsolutePath());
msg.append("File failed !");
logger.excepFuncDebugLog(msg.toString());
throw e;
}
finally
{
if (null != srcIo)
{
srcIo.close();
}
}
}
private static void copyStream(InputStream src, File dst,
final long byteCount) throws Exception
{
FileChannel srcChannel = null;
FileChannel dstChannel = null;
BufferedInputStream in = null;
OutputStream out = null;
FileOutputStream fOut = null;
try
{
if (!dst.exists())
{
boolean flag = dst.createNewFile();
if (!flag)
{
logger.excepFuncDebugLog("create file is failed");
}
}
if (src instanceof FileInputStream && byteCount > -1)
{
srcChannel = ((FileInputStream)src).getChannel();
fOut = new FileOutputStream(dst);
dstChannel = fOut.getChannel();
if (VIRTUAL_MEMORY_SIZE > byteCount)
{
srcChannel.transferTo(0, srcChannel.size(), dstChannel);
}
else
{
long postion = 0;
while (byteCount > postion)
{
long needCopyByte = byteCount - postion;
if (needCopyByte > VIRTUAL_MEMORY_SIZE)
{
needCopyByte = VIRTUAL_MEMORY_SIZE;
}
postion += srcChannel.transferTo(postion,
needCopyByte,
dstChannel);
}
}
}
else
{
in = new BufferedInputStream(src, BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("file copy failure");
throw e;
}
finally
{
try
{
if (null != dstChannel)
{
dstChannel.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("dstChannel close failure");
}
try
{
if (null != fOut)
{
fOut.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("fOut close failure");
}
try
{
if (null != srcChannel)
{
srcChannel.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("srcChannel close failure");
}
try
{
if (null != in)
{
in.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("in close failure");
}
try
{
if (null != out)
{
out.close();
}
}
catch (Exception e)
{
logger.excepFuncDebugLog("out close failure");
}
}
}
/**
* 得到图片文件的BufferedImage对象(用于获取图片的相关属性: 尺寸等)
* @param url
* @return
* @throws IOException
* @return BufferedImage
* @exception throws
*/
public static BufferedImage fileToImage(String url) throws IOException
{
File file = new File(url);
FileInputStream is = new FileInputStream(file);
BufferedImage sourceImg = javax.imageio.ImageIO.read(is);
return sourceImg;
}
}
FileMgrTools:
package com.xxx.dhm.portalMS.common.util;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import com.xxx.dhm.common.config.impl.XMLFactory;
/**
* ClassName:FileMgrTools
* 文件操作工具类,包括对文件夹和文件的操作
* @author
* @version
* @since Ver 1.1
* @Date
*/
public class FileMgrTools
{
public static final Logger logger = Logger.getLogger(FileMgrTools.class);
/**
* 删除文件夹
* @param path
* @return
* @throws Exception
*/
public static void deleteFile(File file)
{
if (file.exists())
{ // 判断文件是否存在
if (file.isFile())
{ // 判断是否是文件
boolean b = file.delete(); // delete()方法 你应该知道 是删除的意思;
if (b)
{
logger.debug("delete success...");
}
}
else if (file.isDirectory())
{ // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++)
{ // 遍历目录下所有的文件
deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
}
}
boolean b = file.delete();
if (b)
{
logger.debug("delete success...");
}
}
else
{
logger.debug("file not exist!");
}
}
/**
* 创建一个文件夹
* @param path
* @return
* @throws Exception
*/
public static boolean createFolder(String path) throws Exception
{
File dirFile = null;
boolean isCreate = true;
try
{
logger.debug("create file folder...");
dirFile = new File(path);
// 判断文件夹是否已存在
boolean isExist = dirFile.exists();
if (!isExist)
{
// 文件夹不存在,则创建一个
isCreate = dirFile.mkdirs();
}
}
catch (Exception e)
{
throw e;
}
return isCreate;
}
/*
* 删除一个文件夹
* @param path
* @return
* @throws Exception
*
public static boolean deleteFolder(String path) throws Exception{
try{
logger.debug("删除文件夹...");
}catch(Exception e){
throw e;
}
return true;
}
*/
/**
* 从磁盘查找文件是否存在
* @param path
* @param fileName
* @return true:存在 false:不存在
* @throws Exception
*/
public static boolean isFileExists(String path, String fileName) throws Exception
{
boolean isExists = false;
File file = null;
try
{
logger.debug("Query file exists ...");
if (fileName == null || "".equalsIgnoreCase(fileName))
{
file = new File(path);
}
else
{
file = new File(path + "/" + fileName);
}
if (file.exists())
{
// 存在返回true
isExists = true;
}
}
catch (Exception e)
{
throw e;
}
return isExists;
}
/**
* 从磁盘读取文件内容
* @param path
* @param fileName
* @return 文件内容(String)
* @throws Exception
*/
public static String getFileContent(String path, String fileName) throws Exception
{
String content = "";
FileInputStream inFile = null;
List<byte[]> bytesList = null;
int byteSize = 0;
try
{
logger.debug("Read the file contents from the disk ...");
// 判断文件是否存在
if (isFileExists(path, fileName))
{
bytesList = new ArrayList<byte[]>();
// 新建文件读取流对象
File in = new File(path + "/" + fileName);
inFile = new FileInputStream(in);
byte[] buffer = new byte[1024];
int i = 0;
logger.debug("Loop to read 1024 bytes ...");
// 循环读取1024字节到bytesList中
while ((i = inFile.read(buffer)) != -1)
{
// byteSize用于保存总字节大小
byteSize += i;
byte[] temp = new byte[i];
// 将读取到的实际大小存入temp中
System.arraycopy(buffer, 0, temp, 0, i);
bytesList.add(temp);
}
// 申请一个总大小的字节空间
byte[] total = new byte[byteSize];
int pos = 0;
logger.debug("Will read the content is stored in a variable ...");
// 将bytesList中内容取出入到总的字节空间中
for (int j = 0; j < bytesList.size(); j++)
{
byte[] temp = bytesList.get(j);
// 将每个临时字节数据存入一个总的字节变量中
System.arraycopy(temp, 0, total, pos, temp.length);
pos += temp.length;
}
String fileEncoding = XMLFactory.getValueString("plugin.staticPage.charSet");
// 按UTF-8编码方式将字节数据转换成字符数据
content = new String(total, fileEncoding);
// content = new
// String(content.getBytes(fileEncoding),Constants.PAGE_ENCODING.getStringValue());
// File f = new File(path + "/" + fileName);
// read = new InputStreamReader(new FileInputStream(f),"UTF-8");
// BufferedReader reader=new BufferedReader(read);
// String line;
// while ((line = reader.readLine()) != null) {
// content += line;
// }
}
}
catch (Exception e)
{
throw e;
}
finally
{
// 关闭打开的文件流
if (inFile != null)
{
inFile.close();
inFile = null;
}
}
return content;
}
/**
* 根据文件内容创建一个磁盘文件
* @param path
* @param fileName
* @param content
* @return
* @throws Exception
*/
public static boolean createFileByContent(String path, String fileName, byte[] content) throws Exception
{
createFolder(path);
DataOutputStream out = null;
File file = null;
boolean isCreate = true;
try
{
logger.debug("Create a disk file according to the content ...");
// 新建一个文件句柄
file = new File(path + "/" + fileName);
// 如果文件已存在则先删除
if (file.exists())
{
// 如果删除失败,控制下面不再写文件
isCreate = file.delete();
}
else
{
// 文件不存在则创建一个空文件,如果创建失败,控制下面不再写文件
isCreate = file.createNewFile();
}
// 如果删除或创建文件成功,则写入文件内容
if (isCreate)
{
// 新建一个文件输入流对象
out = new DataOutputStream(new FileOutputStream(file));
// 将内容写入创建的文件中
out.write(content);
}
}
catch (Exception e)
{
throw e;
}
finally
{
// 关闭创建的文件流
if (out != null)
{
out.close();
out = null;
}
}
return isCreate;
}
/**
* 根据源和目的复制一个文件
* @param orgPath
* @param orgFileName
* @param destPath
* @param destFileName
* @return
* @throws Exception
*/
public static boolean copyFile(String orgPath, String orgFileName, String destPath, String destFileName)
throws Exception
{
FileInputStream inFile = null;
FileOutputStream outFile = null;
boolean isCopy = true;
String org = null;
String dest = null;
try
{
// 判断源文件是否存在
if (isFileExists(orgPath, orgFileName))
{
// 新建源和目标文件句柄
if (orgFileName == null || orgFileName.equalsIgnoreCase(""))
{
org = orgPath;
}
else
{
org = orgPath + "/" + orgFileName;
}
if (destFileName == null || destFileName.equalsIgnoreCase(""))
{
dest = destPath;
}
else
{
dest = destPath + "/" + destFileName;
}
File orgFile = new File(org);
File destFile = new File(dest);
//创建目录
File destDir = new File(destPath);
if (!destDir.exists())
{
boolean flag = destDir.mkdirs();
if (flag)
{
logger.debug("this directory is created successful...");
}
}
if (destFile.exists())
{
// 如果删除失败,控制下面不再复制文件
isCopy = destFile.delete();
}
if (isCopy)
{
// 创建源和目标文件的流对象
inFile = new FileInputStream(orgFile);
outFile = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int i = 0;
// 从源文件中每次读取1024字节存入目标文件
while ((i = inFile.read(buffer)) != -1)
{
outFile.write(buffer, 0, i);
}
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
closeStream(inFile, outFile);
}
return isCopy;
}
private static void closeStream(FileInputStream inFile, FileOutputStream outFile)
{
// 关闭目标文件流对象
if (outFile != null)
{
try
{
outFile.close();
}
catch (Exception e)
{
outFile = null;
}
}
// 关闭源文件流对象
if (inFile != null)
{
try
{
inFile.close();
}
catch (Exception e)
{
inFile = null;
}
}
}
/*
* 删除一个文件
* @param path
* @param fileName
* @return
* @throws Exception
*
public static boolean deleteFile(String path, String fileName) throws Exception{
try{
logger.debug("删除一个文件...");
}catch(Exception e){
throw e;
}
return true;
}
*/
/**
* 文件夹镜象对拷
* @param orgPath 源文件夹路径
* @param destPath 目标文件夹路径
* @param copySubFolder 是否拷贝子文件件
* @return
* @throws Exception
*/
public static boolean folderCopy(String orgPath, String destPath, boolean copySubFolder) throws Exception
{
boolean isCopy = true;
try
{
if (isFileExists(orgPath, null))
{
logger.debug("The folder image copy ...");
// 创建目标文件夹
createFolder(destPath);
// 获取源文件夹的文件列表
File[] fileList = getFolderFilesList(orgPath);
if (fileList != null && fileList.length > 0)
{
logger.debug("Copy the file to the target folder ...");
// 一个一个复制文件到目标文件夹
for (int i = 0; i < fileList.length; i++)
{
// 调用复制方法完成文件的复制功能
isCopy = copyFile(orgPath, fileList[i].getName(), destPath, fileList[i].getName());
// 如果有一个文件复制失败,则整个复制失败
if (!isCopy)
{
break;
}
}
}
}
}
catch (Exception e)
{
throw e;
}
return isCopy;
}
/**
* 文件夹镜象对拷-根据过滤条件
* @param orgPath 源文件夹路径
* @param destPath 目标文件夹路径
* @param copySubFolder 是否拷贝子文件件
* @return
* @throws Exception
*/
public static boolean folderCopyByFileFilter(String orgPath, String destPath, FileFilter fileFilter)
throws Exception
{
boolean isCopy = true;
try
{
if (isFileExists(orgPath, null))
{
// 拷贝当前目录下的文件
folderCopy(orgPath, destPath, false);
// 拷贝当前目录下未被fileFilter过滤的子文件夹文件
File[] subFolderList = getSubFolderList(orgPath, fileFilter);
if (subFolderList != null && subFolderList.length > 0)
{
String folderName = null;
String subOrgPath = null;
String subDestPath = null;
for (int j = 0; j < subFolderList.length; j++)
{
if (subFolderList[j].isDirectory())
{
folderName = subFolderList[j].getName();
subOrgPath = orgPath + "/" + folderName;
subDestPath = destPath + "/" + folderName;
// 子文件件拷贝(嵌套)
isCopy = folderCopyByFileFilter(subOrgPath, subDestPath, fileFilter);
if (!isCopy)
{
break;
}
}
}
}
}
}
catch (Exception e)
{
throw e;
}
return isCopy;
}
/**
* 获取文件夹下子文件夹列表-根据过滤条件
* @param path
* @return
* @throws Exception
*/
private static File[] getSubFolderList(final String path, FileFilter fileFilter) throws Exception
{
File[] fileList = null;
try
{
logger.debug("Suddenly get folder folder list -According to the filtering conditions ...");
if (path != null && !"".equalsIgnoreCase(path))
{
// 创建一个文件句柄
File dir = new File(path);
// 读取文件列表
fileList = dir.listFiles(fileFilter);
// 文件列表排序
if (fileList != null && fileList.length > 0)
{
Arrays.sort(fileList);
}
}
}
catch (Exception e)
{
throw e;
}
return fileList;
}
/**
* 获取文件夹下文件列表
* @param path
* @return
* @throws Exception
*/
private static File[] getFolderFilesList(final String path) throws Exception
{
File[] fileList = null;
try
{
logger.debug("Gets the file folder list ...");
// 创建一个内部类实现文件夹过滤,只罗列文件,不罗列文件夹
FileFilter filter = new FileFilter()
{
public boolean accept(File pathname)
{
boolean isAccept = false;
// 过滤文件夹和以__.为名的临时生成的文件
if (pathname.isFile())
{
String fileName = pathname.getName();
if (fileName != null && fileName.indexOf("__.") < 0)
{
isAccept = true;
}
}
return isAccept;
}
};
if (path != null && !"".equalsIgnoreCase(path))
{
// 创建一个文件句柄
File dir = new File(path);
// 读取文件列表
fileList = dir.listFiles(filter);
// 文件列表排序
if (fileList != null && fileList.length > 0)
{
Arrays.sort(fileList);
}
}
}
catch (Exception e)
{
throw e;
}
return fileList;
}
public static String getRootPath(String curretpath, boolean isFile)
{
if (null == curretpath || "".equals(curretpath))
{
return curretpath;
}
File f = new File(curretpath);
curretpath = f.getPath();
int tmp = 0;
StringBuffer buf = new StringBuffer();
while ((tmp = curretpath.indexOf("/", tmp)) != -1)
{
tmp++;
if (isFile)
{
isFile = false;
continue;
}
buf.append("..").append("/");
}
return buf.toString().equals("") ? "" : buf.toString().substring(0, buf.length() - 1);
}
}
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ include file="../common/language.jsp" %>
<%
String contextPath = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><s:text name="msg.portalMS.channelMgr.assignChannelLenovo" /></title>
<link href="../style/base<%=language_css%>.css" rel="stylesheet" type="text/css" />
<link href="../style/ext-all.css" rel="stylesheet" type="text/css" />
<%@ include file="../common/commonJS.jsp" %>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/dialogShow.js"></script>
<script type="text/javascript" src="../js/validateform.js"></script>
<script type="text/javascript">
function showList(event,day)
{
document.getElementById("tabPageId").value = day;
//归属地
var cityId = $("#cityId").val();
if(day==1){
var tli = document.getElementById("tab_nav").getElementsByTagName("li");
tli[0].className="draw_on";
tli[1].className="";
var resourceId = document.getElementById("hid").value;
var url = "<%=request.getContextPath()%>/channel/findAssignOrNoAssignLenovo.action"
+ "?channel.resourceId="+resourceId
+ "&channel.cityId=" + cityId
+ "&action=association";
mainAssetTypeFrame.location.href= url;
return false;
}
else if(day==2){
var tli = document.getElementById("tab_nav").getElementsByTagName("li");
tli[0].className="";
tli[1].className="draw_on";
var resourceId = document.getElementById("hid").value;
var url = "<%=request.getContextPath()%>/channel/findAssignOrNoAssignLenovo.action"
+ "?channel.resourceId="+resourceId
+ "&channel.cityId=" + cityId
+ "&action=noassociation";
mainAssetTypeFrame.location.href= url;
return false;
}
return false;
}
function showList1(day)
{
var tli = document.getElementById("tab_nav").getElementsByTagName("li");
tli[0].className="draw_on";
tli[1].className="";
//document.getElementById("assetTypeDiv").style.display="none";
document.getElementById("tabPageId").value = "1";
var resourceId = document.getElementById("hid").value;
var cityId = $("#cityId").val();
var url = "<%=request.getContextPath()%>/channel/findAssignOrNoAssignLenovo.action?channel.resourceId=" + resourceId
+ "&channel.cityId=" + cityId
+ "&action=association";
mainAssetTypeFrame.location.href = url;
}
</script>
</head>
<body οnlοad="showList1(1)">
<form id="typeTree" name="typeTree" action="" method="post">
<input id="assetTypeId" type="hidden" name="assetTypeId" />
<input id="tabPageId" type="hidden" name="tabPageId" />
<input id="cityId" type="hidden" name="channel.cityId" value="<s:property value="channel.cityId"/>"/>
<div id="top_blank"></div>
<!---导航 --->
<div class="r_nav">
<div class="left"><img src="../images/nav_l.gif" width="5"
height="29" /></div>
<div class="ct"><s:text name="msg.portalMS.channelTypemgr.current.position" />
<s:text name="msg.portalMS.businessmanagement.name" /> ><s:text name="msg.portalMS.channelMgr.name" /> > <s:text name="msg.portalMS.channelMgr.assignChannelLenovo" /></div>
<div class="right"><img src="../images/nav_r.jpg" width="5"
height="29" /></div>
</div>
<div class="tab_main">
<div id="tab_switchdraw">
<s:hidden id="hid" name="channel.resourceId" />
<ul id="tab_nav">
<li οnclick="showList(event,1)" class="draw_on">
<s:text name="msg.portalMS.channelMgr.assignChannelLenovo.result" />
</li>
<li οnclick="showList(event,2)" ><s:text name="msg.portalMS.channelMgr.assignChannelLenovo.hand" />
</li>
</ul>
</div>
</div>
<div id="cdata_list" style="margin-left: 5px">
<iframe src=""
name="mainAssetTypeFrame" width="100%"
frameborder="0" id="mainAssetTypeFrame" title="mainAssetTypeFrame" scrolling="no" />
</div>
</form>
</body>
</html>