开发者博客:[url]http://www.developsearch.com[/url]
/**
* 解压缩帮助类
*
* @author chenxin
* @version [版本号, 2012-5-21]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class UnzipUtil {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(UnzipContentHelper.class);
/**
*
* 解开压缩
*
* @param contentNo contentno
* @param sourcePath 原epub书籍路劲
* @param targetPath 目标epub书籍路劲 只到保存跟路径
* @see [类、类#方法、类#成员]
*/
public void unZip(String contentNo, String sourcePath, String targetPath)
throws Exception
{
// 查看资源是否存在
File resourceFile = new File(sourcePath);
// 如果资源不存在 就抛出异常
if (!resourceFile.exists())
{
throw new Exception("资源 " + resourceFile.getPath() + " 不存在");
}
File targetFileDir = new File(targetPath);
// 保存目录是否存在
if (!targetFileDir.exists())
{
if (logger.isDebugEnabled())
logger.debug("!targetFileDir.exists()=" + targetFileDir.getPath());
targetFileDir.mkdir();
}
// 创建临时目录
File targetFileDirEpub = new File(targetPath + "/" + contentNo + "_temp");
if (!targetFileDirEpub.exists())
{
if (logger.isDebugEnabled())
logger.debug(targetFileDirEpub.getPath());
targetFileDirEpub.mkdir();
}
// 组装shell脚本
File file = File.createTempFile("unZip", ".sh");
write(file, contentNo, sourcePath, targetPath);
// 复制文件
int retVal = shell("sh " + file.getPath());
// 如果不等于0 表示执行失败
if (logger.isDebugEnabled())
logger.debug("retVal=" + retVal);
if (retVal != 0)
{
throw new Exception("脚本执行出错");
}
}
private int shell(String cmd)
{
int retVal = 1;
if (logger.isInfoEnabled())
logger.info(cmd);
try
{
Process process = java.lang.Runtime.getRuntime().exec(cmd);
retVal = process.waitFor();
}
catch (Exception e)
{
e.printStackTrace();
}
return retVal;
}
private void write(File file, String contentNo, String sourcePath, String targetPath)
{
FileWriter fw = null;
try
{
fw = new FileWriter(file);
fw.write("cp " + sourcePath + " " + targetPath + "/" + contentNo + "_temp/");
fw.write("\n");
fw.write("cd " + targetPath + "/" + contentNo + "_temp");
fw.write("\n");
fw.write("unzip -o -q *.epub");
fw.write("\n");
fw.write("rm *.epub");
fw.write("\n");
fw.write("cd ..");
fw.write("\n");
fw.write("rm -fR " + contentNo);
fw.write("\n");
fw.write("mv " + contentNo + "_temp " + contentNo);
fw.write("\n");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (fw != null)
fw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
// /data/lgftp/resource/2011/2/22/7a8a51bb-aaad-4f12-8bb1-3a18140fe9a1.epub
UnzipContentHelper unzip = new UnzipContentHelper();
try
{
unzip.unZip("123124",
"/data/lgftp/resource/2011/2/22/7a8a51bb-aaad-4f12-8bb1-3a18140fe9a1.epub",
"/data/lgftp/ebook");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}