package com.founder.photo;
/**
* @时间: Sep 10, 2008 9:27:37 AM
* @类说明:遍历原目录下的文件到新目录下-并改变数据库中对应的bfile指针
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.log4j.Logger;
public class FileArrayList
{
static Logger infoLogger = Logger.getLogger("INFO_FILE"); // 记录信息
static Logger errorLogger = Logger.getLogger("ERROR_FILE"); // 记录错误信息
private String url = PropertyFile.getValue("db.oracle.url");
private String dbUserName = PropertyFile.getValue("db.user.name");
private String dbUserPassword = PropertyFile.getValue("db.user.password");
static String OLD_PATH = "C:/image/photo/images0"; // 新华图片系统-老路径
// TODO 填写新的数据库Directory名称
private static String NEW_BFILE_DIR = "c:/image/NWKPHOTO";
final private static String SQL_QUERY = "select PHOTO_LOB_ID ,SYS_CREATED from dom_3_doclib where sys_documentid=?";
final private static String SQL_QUERY_DATE = "select PHOTO_OPERATION_DATE from photo_operation_record where sys_documentid=? and photo_operation_id in (23,38,106)";
final private static String SQL_UPDATE = "update dom_image_lob set ext_large=bfilename('"
+ NEW_BFILE_DIR + "',?) where sys_lob_id=?";
private PreparedStatement pst_Get_Photo;
private PreparedStatement pst_Update_Bfile;
private PreparedStatement pst_Get_Date;
private Connection conn = null;
public static void main(String[] args) throws IOException, SQLException
{
FileArrayList fal = new FileArrayList();
fal.refreshFileList(OLD_PATH);
}
/**
* 数据库创建连接
*/
public void getPreparedStatement() throws SQLException
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
conn = DriverManager.getConnection(url, this.dbUserName,
this.dbUserPassword);
this.pst_Get_Photo = this.conn.prepareStatement(SQL_QUERY);
this.pst_Get_Date = this.conn.prepareStatement(SQL_QUERY_DATE);
this.pst_Update_Bfile = this.conn.prepareStatement(SQL_UPDATE);
}
/**
* 创建目录
*/
public void createCatalog(String new_path)
{
boolean bFile = false;
try
{
File dirFile = new File(new_path);
bFile = dirFile.exists();
if (!bFile)
{
infoLogger.info(new_path + "目录不存在,现在就创建...");
bFile = dirFile.mkdirs();
if (bFile == true)
{
infoLogger.info("创建成功!开始写入文件...");
} else
{
throw new RuntimeException("创建目录失败!请检查环境配置");
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 遍历原目录下的所有文件
*/
public void refreshFileList(String oldPath)
{
try
{
this.getPreparedStatement();
ArrayList filelist = new ArrayList();
File dir = new File(oldPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files == null)
return;
for (int i = 0; i < files.length; i++)
{
String fileName = files[i].getName().trim().toLowerCase();
// 判断是文件还是文件夹
if (files[i].isDirectory()
&& !files[i].getName().startsWith("."))
{
refreshFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
} else if (fileName.endsWith("jpg") || fileName.endsWith("bmp")
|| fileName.endsWith("gif"))
{
String strFileName = files[i].getAbsolutePath();
filelist.add(files[i].getAbsolutePath());
int sysId = this.getSysId(fileName); // 取出文件名做where条件查询数据库
String type = fileName.substring(
fileName.lastIndexOf(".") + 1, fileName.length());
// --------------取出年月创建文件夹,取出photoId查询dom_image_lob-----
pst_Get_Photo.setInt(1, sysId);
ResultSet rs = pst_Get_Photo.executeQuery();
int photoId = 0;
String yearNum = null, monthNumber = null;
if (rs.next())
{
photoId = rs.getInt("PHOTO_LOB_ID");
// TODO 正式用的时间
String strDate = getDateStr(getPhotoDate(sysId, rs
.getDate("SYS_CREATED")));
// String strDate = getDateStr(getPhotoDate(sysId, rs
// .getDate("FLOW_SIGNDATE")));
yearNum = strDate.substring(0, 4);
monthNumber = strDate.substring(4);
if (monthNumber.startsWith("0"))
monthNumber = monthNumber.substring(1);
}
rs.close();
pst_Get_Photo.clearParameters();
if (photoId == 0 || yearNum == null || monthNumber == null)
{
errorLogger.info(fileName + "在文件系统中存在,但数据库无记录匹配");
continue;
} else
{
// TODO 暂时的new_path固定,待从数据库中取出
String new_path = NEW_BFILE_DIR + "/" + yearNum + "/"
+ monthNumber + "/";
this.createCatalog(new_path);
this.movePhoto(strFileName, sysId, type, yearNum,
monthNumber, photoId, new_path);
infoLogger.info(fileName + "写入完成!");
this.updateNewPath(photoId, type, yearNum, monthNumber,
sysId);
}
} else
{
continue;
}
}
errorLogger
.info("----------------------------------------------------操作完成-----");
infoLogger
.info("----------------------------------------------------操作完成-----");
} catch (SQLException e)
{
errorLogger.error(e);
} finally
{
this.close();
}
}
/**
* 获取图片原始上传时间,如果从操作记录中找不到,则用FLOW_SIGNDATE作为备选代替
*
* @param docId
* @param backDate
* @return
*/
private Date getPhotoDate(int docId, Date backDate)
{
ResultSet rs = null;
try
{
pst_Get_Date.setInt(1, docId);
rs = pst_Get_Date.executeQuery();
if (rs.next())
return rs.getDate(1);
} catch (Exception ex)
{
ex.printStackTrace();
} finally
{
if (rs != null)
try
{
rs.close();
} catch (SQLException e)
{
e.printStackTrace();
}
if (pst_Get_Date != null)
try
{
pst_Get_Date.clearParameters();
} catch (SQLException e)
{
e.printStackTrace();
}
}
return backDate;
}
/**
* 生成200809格式的日期
*
* @param date
* @return
*/
private static String getDateStr(Date date)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
if (date == null)
return null;
return sdf.format(date);
}
/**
* 传入文件名, 去数据库对应sysId
*
* @strFileName = 路径+文件名
*/
public int getSysId(String strFileName)
{
String test = strFileName.substring(0, strFileName.lastIndexOf("."));
int sysId = Integer.parseInt(test);
return sysId;
}
/**
* 移动图片
*/
public void movePhoto(String strFileName, int sysId, String type,
String yearNum, String monthNumber, int photoId, String new_path)
{
FileInputStream fis = null;
FileOutputStream fos = null;
byte[] buff = new byte[1024];
try
{
fis = new FileInputStream(strFileName);
File file = new File(new_path + sysId + "." + type);
if (file.exists())
{
infoLogger.info(strFileName + "与现有文件重名...将原文件加入时间戳备份");
this.modifyFileName(file, sysId, type, new_path);
fos = new FileOutputStream(new_path + sysId + "." + type);
} else
{
fos = new FileOutputStream(file);
}
int n = 0;
while ((n = fis.read(buff)) != -1)
{
fos.write(buff, 0, n);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
errorLogger.info("没有找到文件" + strFileName);
} catch (IOException e)
{
e.printStackTrace();
errorLogger.info("处理文件" + strFileName + "异常," + e.getMessage());
} finally
{
try
{
fos.close();
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 如果目录下有此文件,则修改文件名(加入时间戳)
*/
public void modifyFileName(File oldFile, int sysId, String type,
String new_path)
{
// File file = new File( new_path + sysId +"."+ type ); // 指定文件名及路径
// String filename = file.getAbsolutePath();
// if ( filename.indexOf( "." ) >= 0 )
// {
// filename = filename.substring( 0, filename.lastIndexOf( "." ) );
// }
// 取出系统时间
SimpleDateFormat sdf = new SimpleDateFormat("ddHHmmss");
String time = sdf.format(new Date());
oldFile.renameTo(new File(new_path + sysId + "_" + time + "." + type
+ ".bak")); // 更改文件名
}
/**
* 修改新图片的路径
*/
public void updateNewPath(int photoId, String type, String yearNum,
String monthNumber, int sysId) throws SQLException
{
String newPath = "/" + yearNum + "/" + monthNumber + "/" + sysId + "."
+ type;
try
{
pst_Update_Bfile.setString(1, newPath);
pst_Update_Bfile.setInt(2, photoId);
int result = pst_Update_Bfile.executeUpdate();
if (result != 1)
throw new SQLException("更新PHOTO_LOB_ID为" + photoId + "的稿件失败!");
} finally
{
pst_Update_Bfile.clearParameters();
}
}
/**
* 关闭数据库连接
*/
public void close()
{
if (this.pst_Get_Date != null)
try
{
pst_Get_Date.close();
} catch (SQLException e1)
{
e1.printStackTrace();
}
if (this.pst_Get_Photo != null)
try
{
pst_Get_Photo.close();
} catch (SQLException e1)
{
e1.printStackTrace();
}
if (this.pst_Update_Bfile != null)
try
{
pst_Update_Bfile.close();
} catch (SQLException e1)
{
e1.printStackTrace();
}
if (conn != null)
{
try
{
conn.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
}