您的位置:首页 > 其它

报表抽数据

2015-11-03 18:03 337 查看
根据配置文件 获取数据库连接 根据配置信息读取数据库数据 将数据写人本地文件中 将文件传输到FTP服务器上

<bean id="cdrTask" class="com.coship.report.task.BaseReportTask">

<property name="sqlMapClient">

<ref bean="sqlMapClient_iepg" />

</property>

<!-- Ftp properties -->

<property name="ftpIp">

<value>172.20.33.3</value>

</property>

<property name="ftpPort">

<value>21</value>

</property>

<property name="ftpUser">

<value>908251</value>

</property>

<property name="ftpPassword">

<value>908251</value>

</property>

<property name="ftpPath">

<value>/home/908251</value>

</property>

<property name="sqlId">

<value>cdrTask</value>

</property>

<!--

<property name="sqlIdAll">

<value>cdrTaskAll</value>

</property>

-->

<property name="perPagerRows">

<value>10000</value>

</property>

<property name="localTmpFilePath">

<value>F:\tmp\</value>

</property>

<property name="writeColumns">

<value>CDR_ID,USER_ID,DEVICE_ID,BEGINDATE,START_TIME,END_TIME,PLAY_TIME,PLAY_TYPE,RESOURCE_ID,ASSET_ID,GOODS_CODE,PRODOFFERING_CODE,RESOURCE_NAME,SESSION_ID,PLAY_PATH,PROGRAM_PATH,COLUMN_ID,GOODS_NAME,EVENT_START_TIME,EVENT_END_TIME,SUB_ID,ORDER_TYPE,REASON_CODE,STATUS,CREATE_TIME</value>

</property>

<property name="fileMaxRows">

<value>100000</value>

</property>

<property name="moduleName">

<value>cdrTask</value>

</property>

<property name="applicationName">

<value>dhm</value>

</property>

<property name="beforePrefix">

<value></value>

</property>

<property name="afterPrefix">

<value></value>

</property>

<property name="columnPrefix">

<value>],[</value>

</property>

</bean>

<bean id="dataSource_iepg" class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>

<property name="url" value="jdbc:oracle:thin:@172.21.11.142:1521:corac"/>

<property name="username" value="fs_iepg_727"/>

<property name="password" value="coship"/>

<property name="initialSize" value="5" />

<property name="maxActive" value="100"/>

<property name="maxIdle" value="30" />

<property name="maxWait" value="1000" />

<property name="poolPreparedStatements" value="true"/>

<property name="defaultAutoCommit" value="true" />

<property name="removeAbandoned" value="true" />

<property name="removeAbandonedTimeout" value="5" />

</bean>

package com.xxxxxx.report.task;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStreamWriter;

import java.sql.Connection;

import java.sql.SQLException;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.GregorianCalendar;

import java.util.HashMap;

import java.util.Hashtable;

import java.util.List;

import java.util.Map;

import org.apache.log4j.Logger;

import com.xxxxxx.report.ftp.util.FtpLoginInfo;

import com.xxxxxx.report.ftp.util.FtpUtil;

import com.xxxxxx.report.util.Constant;

import com.xxxxxx.report.util.xxxxxxSqlMapClientDaoSupport;

import com.xxxxxx.report.util.DateUtil;

import com.xxxxxx.report.util.FileTool;

import com.xxxxxx.report.util.QueryPageDTO;

import com.xxxxxx.report.util.StringUtil;

/**

* 数据源提取主程序

*

* @author

*

*/

public class BaseReportTask extends xxxxxxSqlMapClientDaoSupport implements

Runnable {

protected String ftpIp;

protected Integer ftpPort;

protected String ftpUser;

protected String ftpPassword;

protected String ftpPath;

//FTP上传文件方式,1-绝对路径方式 2-相对路径方式

protected String ftpMethod;

protected String localTmpFilePath; // 临时目录,存放临时文件和运行文件

protected Integer fileMaxRows; // 每个文件的最大行数

protected Integer perPagerRows; // 分页取数据的每页最大行数

protected String moduleName; // 接口名称或者报表名称

protected String applicationName;// 接口应用名称

protected String sqlId; // 执行吸取数据的SQL

protected String writeColumns; // 以逗号分割的各个字段名称

protected String beforePrefix = ""; // 分隔符前缀

protected String afterPrefix = ""; // 分隔符后缀

protected String columnPrefix = ""; // 分隔符

protected String defaultDate;// 查询时间

protected String baseTableName;//爱渡飞基础表名

protected static String PTAH_SPLIT = "/";

protected String fileName = "";

protected Map<String, String> tmpFiles = new Hashtable<String, String>();

@SuppressWarnings("unchecked")

protected ThreadLocal local = new ThreadLocal();

private static Logger log = Logger.getLogger(BaseReportTask.class);

/**

* 最后的日期跑过的次数的日期要写到日志中

*/

public synchronized void run() {

try {

long start = System.currentTimeMillis();

log.info(moduleName + "-提取数据任务-开始");

// 吸取数据,并产生临时文件

boolean isData = seakData();

// FTP文件的传输

// 2011-11-3 没有记录时也生成文件夹 应报表要求 905827

ftpFile();

long end = System.currentTimeMillis();

log.info(moduleName + "-提取数据任务-结束-耗时:" + (end - start) + "MS.");

} catch (Exception ex) {

log.error(ex);

}

}

/**

* 通过指定的SQL,从数据库中抓取数据,并写入临时文件

*/

@SuppressWarnings("unchecked")

protected boolean seakData() {

// 清空上传列表

tmpFiles.clear();

// 获取生成文件的文件名

fileName = getFileName();

log.info(moduleName + "-步骤1/5-提取数据任务-生成文件名-" + fileName);

QueryPageDTO page = new QueryPageDTO();

page.setBeginIndex(1);

page.setEndIndex(perPagerRows);

Connection conn=null;

try {

conn=getSqlMapClientTemplate().getDataSource().getConnection();

page.setDatabase(conn.getMetaData().getDatabaseProductName());

Map<String, Object> map = new HashMap<String, Object>();

if (StringUtil.isEmpty(defaultDate)) {

map.put("defaultDate", new Date());

} else {

try {

map.put("defaultDate",

new SimpleDateFormat("yyyy-MM-dd").parse(defaultDate));

} catch (ParseException e) {

e.printStackTrace();

log.error("error date format for defaultDate!");

return false;

}

}

if(this.moduleName.startsWith(Constant.OTT_RANK)){

//爱渡飞OTT频道排行接口

Calendar cal=GregorianCalendar.getInstance();

int month=cal.get(Calendar.MONTH);

String tableName=null;

if(Constant.FIRST_MONTH==month){//第1月为0

tableName=baseTableName;

}else{

tableName=baseTableName+month;

}

map.put("table", tableName);

log.info("OTT详单表名:"+tableName);

}

// 按配置的分页查询数查询数据

List datas = this.queryForList(sqlId, map, page);

if (datas == null || datas.size() <= 0) {

return false;

}

// 分页进行抓取数据

int totalCount = page.getAllCount();

int totalPageCount = totalCount / perPagerRows + 1;

log.info(moduleName + "-步骤2/5-提取数据任务-数据量-" + totalCount);

writeText(datas, localTmpFilePath);

for (int i = 1; i < totalPageCount; i++) {

page.setBeginIndex(i * perPagerRows + 1);

page.setEndIndex((i + 1) * perPagerRows);

datas = this.queryForList(sqlId, map, page);

writeText(datas, localTmpFilePath);

}

} catch (SQLException e1) {

e1.printStackTrace();

}finally{

try {

conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return true;

}

public static void main(String[] args) {

Date date=new Date();

System.out.println(DateUtil.format(date)+" "+date.getMonth());

}

/**

* 处理文件,发送FTP服务器,并且删除临时文件 1.在FTP上生成文件件 2.将临时文件传入FTP服务器

*

* @throws java.io.IOException

*/

protected void ftpFile() throws java.io.IOException {

FileTool ft = new FileTool();

FtpUtil fu = new FtpUtil();

try {

// FTP登陆

login(fu);

// 生成文件夹

String fullPath = getFullPath();

fu.createFolder(fullPath, PTAH_SPLIT);

log.info(moduleName + "-步骤3/5-提取数据任务-创建上传路径-" + fullPath);

// 在本地生成空start文件

ft.createFile(localTmpFilePath +"start", "");

File file1 = new File(localTmpFilePath + "start");

// if(!file1.exists()){

// file1.createNewFile();

// }

log.info(moduleName + "-提取数据任务-在本地创建空临时文件-" + localTmpFilePath + "start");

// 传入文件之前先创建一个空的start文件到FTP

if(ftpMethod == "1")

fu.uploadFile(ftpPath + PTAH_SPLIT + fullPath + PTAH_SPLIT + "start", file1);

else

fu.uploadFile(ftpPath + PTAH_SPLIT + fullPath + PTAH_SPLIT, "start", file1);

log.info(moduleName + "-步骤4/5-提取数据任务-文件批量上传列表-" + tmpFiles.keySet());

// 批量上传文件

for (String tmpFile : tmpFiles.values()) {

File file = new File(localTmpFilePath + tmpFile);

if(ftpMethod == "1")

fu.uploadFile(ftpPath + PTAH_SPLIT + fullPath + PTAH_SPLIT + tmpFile, file);

else

fu.uploadFile(ftpPath + PTAH_SPLIT + fullPath + PTAH_SPLIT, tmpFile, file);

log.info(moduleName + "-提取数据任务-文件-" + ftpPath + PTAH_SPLIT

+ fullPath + PTAH_SPLIT + tmpFile + "-已上传至FTP");

}

// 删除本地临时文件

for (String localTmpFile : tmpFiles.values()) {

boolean b = ft.delFile(localTmpFilePath + localTmpFile);

log.info(moduleName + "-提取数据任务-本地文件-" + localTmpFilePath

+ localTmpFile + "-已删除-" + b);

}

log.info(moduleName + "-步骤5/5-提取数据任务-文件批量删除列表-" + tmpFiles.keySet());

if(ftpMethod == "1")

fu.deleteFile(ftpPath + PTAH_SPLIT + fullPath + PTAH_SPLIT + "start");

else

fu.deleteFile(ftpPath + PTAH_SPLIT + fullPath + PTAH_SPLIT, "start");

// 删除本地空文件

// ft.delFile(localTmpFilePath +moduleName+"start");

// 清空MAP

tmpFiles.clear();

} catch (Exception ex) {

log.debug("FTP上传文件失败!");

ex.printStackTrace();

} finally {

fu.close();

}

}

protected void clear() {

tmpFiles.clear();

}

/**

* FTP登陆

*/

private void login(FtpUtil fu) throws java.io.IOException {

FtpLoginInfo login = new FtpLoginInfo();

login.setIp(this.ftpIp);

login.setPort(this.ftpPort);

login.setPwd(this.ftpPassword);

login.setUserName(this.ftpUser);

log.info("ftpIP:"+ftpIp+" ftpUser:"+ftpUser+" ftpPassword:"+ftpPassword);

fu.startClient(login);

}

/**

* 取得FTP上的相对路径

*

* @param year

* @param month

* @param day

* @return

*/

protected String getFullPath() {

Date date = null;

if (!StringUtil.isEmpty(defaultDate)) {

try {

date = new SimpleDateFormat("yyyy-MM-dd").parse(defaultDate);

date = new Date(date.getTime() - 24 * 60 * 60 * 1000);

} catch (ParseException e) {

e.printStackTrace();

}

} else {

date = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);

}

String dateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(date);

String year = dateStr.split("-")[0];

String month = dateStr.split("-")[1];

String day = dateStr.split("-")[2];

if (this.applicationName != null && !this.applicationName.equals("")) {

return applicationName + PTAH_SPLIT + moduleName + PTAH_SPLIT

+ year + PTAH_SPLIT + month + PTAH_SPLIT + day;

} else {

return year + PTAH_SPLIT + month + PTAH_SPLIT + day;

}

}

/**

* 每次都计算文件的当前行数,如果超出配置的行数,则写下一个文件

*

* @param data

* @param fileName

*/

@SuppressWarnings("unchecked")

protected void writeText(List data, String path) {

if (data == null || data.size() <= 0) {

return;

}

FileTool ft = new FileTool();

OutputStreamWriter out = null;

try {

File f = new File(path + fileName);

Integer currentFileNum = 0;

if (f.exists()) {

currentFileNum = ft.readLineCount(path + fileName);

log.info(moduleName + "-提取数据任务-文件-" + fileName + "已存在且已写入"

+ currentFileNum + "行");

}

out = new OutputStreamWriter(new FileOutputStream(path + fileName,

true), "UTF-8");

String[] columnNames = writeColumns.split(",");

// StringBuffer text=new StringBuffer();

for (int i = 0; i < data.size(); i++) {

Map t1 = (Map) data.get(i);

String text = null;

// text.delete(0, text.length());

for (String columnName : columnNames) {

String o = StringUtil.toString(t1.get(columnName));

if (text == null) {

text = beforePrefix + o + afterPrefix;

} else {

text += columnPrefix + beforePrefix + o + afterPrefix;

}

/*

if (text == null || text.length()==0 ) {

text.append(beforePrefix);

text.append(o);

text.append(afterPrefix);

} else {

text.append(columnPrefix);

text.append(beforePrefix);

text.append(o);

text.append(afterPrefix);

}

*/

}

// 如果超过了最大配置的行数,则新产生另外一个文件

if (currentFileNum >= fileMaxRows) {

try {

// 关闭原来的那个文件

if (out != null) {

out.flush();

out.close();

}

log.info(moduleName + "-提取数据任务-文件-" + fileName

+ "已被加入上传列表,继续生成新文件...");

tmpFiles.put(fileName, fileName);

// 新生成一个文件:

Integer fileNum = (Integer) local.get();

fileNum++;

local.set(fileNum);

fileName = getFileName();

log.info(moduleName + "-提取数据任务-文件-" + fileName + "生成");

// 写文件

out = new OutputStreamWriter(new FileOutputStream(path

+ fileName, true), "UTF-8");

currentFileNum = 0;

} catch (Exception ex) {

ex.printStackTrace();

}

}

// 打印和计数

out.write(text + "\n");

currentFileNum++;

out.flush();

}

log.info(moduleName + "-提取数据任务-文件-" + fileName + "已被加入上传列表");

tmpFiles.put(fileName, fileName);

} catch (Exception ex) {

ex.printStackTrace();

} finally {

try {

if (out != null) {

out.flush();

out.close();

}

} catch (Exception ex) {

}

}

}

/**

* 按照一定的规则产生文件的名称 名字为生成日期的前一天

*

* @return

*/

@SuppressWarnings("unchecked")

protected String getFileName() {

Integer fileNum = (Integer) local.get();

if (fileNum == null) {

fileNum = 0;

local.set(fileNum);

}

Date now = null;

if (!StringUtil.isEmpty(defaultDate)) {

try {

now = new SimpleDateFormat("yyyy-MM-dd").parse(defaultDate);

now = new Date(now.getTime() - 24 * 60 * 60 * 1000);

} catch (ParseException e) {

e.printStackTrace();

}

} else {

now = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);

}

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");

String nowStr = format.format(now);

return moduleName + "_0_" + nowStr + "_" + fileNum;

}

public String getFtpIp() {

return ftpIp;

}

public void setFtpIp(String ftpIp) {

this.ftpIp = ftpIp;

}

public Integer getFtpPort() {

return ftpPort;

}

public void setFtpPort(Integer ftpPort) {

this.ftpPort = ftpPort;

}

public String getFtpPath() {

return ftpPath;

}

public void setFtpPath(String ftpPath) {

this.ftpPath = ftpPath;

}

public Integer getFileMaxRows() {

return fileMaxRows;

}

public void setFileMaxRows(Integer fileMaxRows) {

this.fileMaxRows = fileMaxRows;

}

public Integer getPerPagerRows() {

return perPagerRows;

}

public void setPerPagerRows(Integer perPagerRows) {

this.perPagerRows = perPagerRows;

}

public String getModuleName() {

return moduleName;

}

public void setModuleName(String moduleName) {

this.moduleName = moduleName;

}

public String getSqlId() {

return sqlId;

}

public void setSqlId(String sqlId) {

this.sqlId = sqlId;

}

public String getFtpUser() {

return ftpUser;

}

public void setFtpUser(String ftpUser) {

this.ftpUser = ftpUser;

}

public String getFtpPassword() {

return ftpPassword;

}

public void setFtpPassword(String ftpPassword) {

this.ftpPassword = ftpPassword;

}

public String getLocalTmpFilePath() {

return localTmpFilePath;

}

public void setLocalTmpFilePath(String localTmpFilePath) {

this.localTmpFilePath = localTmpFilePath;

}

public String getWriteColumns() {

return writeColumns;

}

public void setWriteColumns(String writeColumns) {

this.writeColumns = writeColumns;

}

public String getBeforePrefix() {

return beforePrefix;

}

public void setBeforePrefix(String beforePrefix) {

this.beforePrefix = beforePrefix;

}

public String getAfterPrefix() {

return afterPrefix;

}

public void setAfterPrefix(String afterPrefix) {

this.afterPrefix = afterPrefix;

}

public String getColumnPrefix() {

return columnPrefix;

}

public void setColumnPrefix(String columnPrefix) {

this.columnPrefix = columnPrefix;

}

public String getApplicationName() {

return applicationName;

}

public void setApplicationName(String applicationName) {

this.applicationName = applicationName;

}

public String getDefaultDate() {

return defaultDate;

}

public void setDefaultDate(String defaultDate) {

this.defaultDate = defaultDate;

}

public String getFtpMethod() {

return ftpMethod;

}

public void setFtpMethod(String ftpMethod) {

this.ftpMethod = ftpMethod;

}

public String getBaseTableName() {

return baseTableName;

}

public void setBaseTableName(String baseTableName) {

this.baseTableName = baseTableName;

}

}

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package com.coship.report.ftp.util;

/**

*

* @author

*/

public class FtpLoginInfo{

private String ip;

private int port;

private String userName;

private String pwd;

public String getIp() {

return ip;

}

public void setIp(String ip) {

this.ip = ip;

}

public int getPort() {

return port;

}

public void setPort(int port) {

this.port = port;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

@Override

public String toString() {

return "ip=="+ip+" port=="+port+" userName=="+userName+" pwd=="+pwd;

}

}

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package com.coship.report.ftp.util;

/**

*处理Ftp的上传,下载

* 1.利用包common-net

* @author

*/

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPFile;

import org.apache.commons.net.ftp.FTPReply;

import org.apache.log4j.Logger;

public class FtpUtil {

// TODO modify

private static Logger log = Logger.getLogger(FtpUtil.class);

private static ThreadLocal currentSession = new ThreadLocal();

private static FtpLoginInfo constLogin = null;

private static final String ENCODEING_UTF = "UTF-8";

/**

* 得到一个登陆成功的Client对象

*

* @param login

* @return

* @throws java.lang.Exception

*/

public void startClient(FtpLoginInfo login) throws java.io.IOException {

if (login == null) {

return;

}

constLogin = login;

FTPClient ftp = new FTPClient();

ftp.setControlEncoding(ENCODEING_UTF);

int reply;

ftp.connect(login.getIp(), login.getPort());

log.debug("连接FTP服务器成功!!" + login.getIp() + " " + login.getPort());

// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器

ftp.login(login.getUserName(), login.getPwd());// 登录

log.debug("连接FTP服务器成功!!" + login.getUserName() + " " + login.getPwd());

/**/

// ftp.setFileType(FTP.LOCAL_FILE_TYPE);

// ftp.enterLocalPassiveMode();

reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect();

log.info("登陆FTP服务器失败!!");

return;

}

currentSession.set(ftp);

log.info("登陆FTP服务器成功!!"+ login.getUserName() + " " + login.getPwd());

}

/**

* 检查一个文件在FTP服务器上的状态 返回值说明: 0:FTP登录信息缺少 1: FTP服务没有开启 2: 该文件不存在 3: 校验失败! 4:

* 正常

*/

public int checkFileStatus(String filePath, String fileName) {

FTPClient client = null;

try {

startClient(constLogin);

client = (FTPClient) currentSession.get();

if (client == null) {

return 0;

}

} catch (Exception ex) {

return 1;

}

if (!client.isConnected()) {

return 1;

}

try {

FTPFile[] files = client.listFiles(filePath);

if (files == null) {

return 2;

}

for (FTPFile ftpFile : files) {

if (ftpFile.getName().equals(fileName)) {

return 4;

}

}

return 2;

} catch (Exception ex) {

ex.printStackTrace();

return 3;

}

}

/**

* 在当前目录 根据传入的路径循环创建目录

*/

public void createFolder(String ftpPath, String split)

throws java.io.IOException {

if (ftpPath == null || ftpPath.equals("") || split == null

|| split.equals("")) {

return;

}

String[] paths = ftpPath.split(split);

// 先判断:prefix目录存不存在

FTPClient client = (FTPClient) currentSession.get();

if (client == null) {

return;

}

for (String path : paths) {

boolean ifExist = client.changeWorkingDirectory(path);

if (!ifExist) {

boolean isSuccess = client.makeDirectory(path);

log.info(this.getClass().getName() + "createFolder "

+ isSuccess + "=" + path);

boolean isSuccess1 = client.changeWorkingDirectory(path);

log.info(this.getClass().getName() + "createFolder "

+ isSuccess1 + "=" + path);

boolean isT = false;

}

}

}

/**

* 显示Ftp文件列表

*

* @param client

* @param fullPath

* @return

* @throws java.io.IOException

*/

public List<FileObj> showFiles(String filePath) throws Exception {

FTPClient client = (FTPClient) currentSession.get();

if (client == null) {

return null;

}

if (!client.isConnected()) {

log.warn("ftpClient is not connected ,now reconected!!");

startClient(constLogin);

}

try {

FTPFile[] files = client.listFiles(filePath);

if (files == null) {

return null;

}

List<FileObj> list = new ArrayList();

for (int i = 0; i < files.length; i++) {

FTPFile file = files[i];

if (file.isFile()) {

FileObj o = new FileObj();

o.setFileName(file.getName());

o.setTime(file.getTimestamp().getTime());

o.setFilePath(filePath);

o.setFileSize(file.getSize());

o.setTabIndex(i);

list.add(o);

}

}

client.logout();

return list;

} catch (java.net.SocketException socketException) {

client.disconnect();

log.error(socketException);

throw socketException;

} catch (Exception ex) {

// ex.printStackTrace();

log.error(ex);

throw ex;

} finally {

if (client != null && client.isConnected()) {

client.disconnect();

}

}

}

/**

* 传入一个完整文件名称,下载到本地

*

* @param client

* @param fullPath

* 带有文件名称的路径

* @param localPath

* 本地路径

* @throws java.io.IOException

*/

public void downLoadFile(String fullPath, String localPath)

throws Exception {

FTPClient client = (FTPClient) currentSession.get();

if (client == null) {

return;

}

OutputStream is = null;

try {

File file = new File(localPath);

is = new FileOutputStream(file);

client.retrieveFile(fullPath, is);

client.logout();

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

throw ex;

} finally {

try {

is.close();

} catch (Exception ex) {

}

if (client != null && client.isConnected()) {

client.disconnect();

}

}

}

public InputStream downLoadFile(String fullPath) throws Exception {

FTPClient client = (FTPClient) currentSession.get();

if (client == null) {

return null;

}

try {

return client.retrieveFileStream(fullPath);

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

throw ex;

} finally {

if (client != null && client.isConnected()) {

client.disconnect();

}

}

}

/**

* 上传一个文件

*

* @param client

* @param fullPath

* @param localFile

*/

public void uploadFile(String fullPath, File localFile) throws Exception {

FTPClient client = (FTPClient) currentSession.get();

boolean upFile;

if (client == null) {

return;

}

InputStream is = null;

try {

is = new FileInputStream(localFile);

upFile = client.storeFile(fullPath, is);

log.debug("文件:" + localFile + " 已提交到 " + fullPath + " --->"

+ upFile);

// client.logout();

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

throw ex;

} finally {

try {

is.close();

} catch (Exception ex) {

}

// if (client != null && client.isConnected()) {

// client.disconnect();

// }

}

}

public void uploadFile(String Path, String remote, File localFile)

throws Exception {

FTPClient client = (FTPClient) currentSession.get();

boolean upFile;

if (client == null) {

return;

}

InputStream is = null;

try {

is = new FileInputStream(localFile);

client.changeWorkingDirectory(Path);

upFile = client.storeFile(remote, is);

log.debug("文件:" + localFile + " 已提交到 " + Path + " --->" + upFile);

if (!upFile) {

log.info("uploadFile client.getReply():" + client.getReply());

log.info("uploadFile client.getReplyString():" + client.getReplyString());

}

// client.logout();

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

throw ex;

} finally {

try {

is.close();

} catch (Exception ex) {

}

// if (client != null && client.isConnected()) {

// client.disconnect();

// }

}

}

/**

* 删除一个文件

*

* @param fullPath

* @return

* @throws Exception

*/

public boolean deleteFile(String fullPath) throws Exception {

FTPClient client = (FTPClient) currentSession.get();

if (client == null) {

return false;

}

try {

// client.deleteFile(fullPath);

boolean isSuccess = client.deleteFile(fullPath);

client.logout();

if (!isSuccess) {

log.info("client.getReply():" + client.getReply());

log.info("client.getReplyString():" + client.getReplyString());

}

log.info("临时文件 ==>>" + fullPath+" 已被删除 "+isSuccess);

return isSuccess;

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

throw ex;

} finally {

if (client != null && client.isConnected()) {

client.disconnect();

}

}

}

public boolean deleteFile(String fullPath, String remote) throws Exception {

FTPClient client = (FTPClient) currentSession.get();

if (client == null) {

return false;

}

try {

// client.deleteFile(fullPath);

client.changeWorkingDirectory(fullPath);

boolean isSuccess = client.deleteFile(remote);

client.logout();

return isSuccess;

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

throw ex;

} finally {

if (client != null && client.isConnected()) {

client.disconnect();

}

}

}

public void close() {

try {

FTPClient client = (FTPClient) currentSession.get();

if (client != null && client.isConnected()) {

client.disconnect();

}

} catch (Exception ex) {

}

}

public boolean deleteFileForMulti(String fullPath) throws Exception {

FTPClient client = (FTPClient) currentSession.get();

if (client == null) {

return false;

}

try {

// client.deleteFile(fullPath);

boolean isSuccess = client.deleteFile(fullPath);

client.logout();

return isSuccess;

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

throw ex;

}

}

public static void main(String[] args) {

try {

System.out.println(new Date().getTime());

FtpLoginInfo info = new FtpLoginInfo();

info.setIp("127.0.0.1");

info.setPort(21);

info.setUserName("root");

info.setPwd("root");

FtpUtil ftpUtil = new FtpUtil();

ftpUtil.startClient(info);

// List<FileObj> list = ftpUtil.showFiles("/");

// if(list==null) return;

// for(FileObj file:list){

// System.out.println(file);

// }

// System.out.println(new Date().getTime());

ftpUtil.downLoadFile("/server.log", "E:\\server.log");

} catch (Exception ex) {

ex.printStackTrace();

log.error(ex);

}

}

public static String getSepartor(String filePath) {

if (filePath == null) {

return "";

}

if (filePath.indexOf("\\") > -1) {

return "\\";

}

if (filePath.indexOf("/") > -1) {

return "/";

}

return File.separator;

}

}

package com.coship.report.util;

import java.sql.SQLException;

import java.util.List;

import java.util.Map;

import org.apache.log4j.Logger;

import org.springframework.dao.DataAccessException;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

/**

* @author

*

*/

public class CoshipSqlMapClientDaoSupport extends SqlMapClientDaoSupport {

private Logger log = Logger.getLogger(CoshipSqlMapClientDaoSupport.class);

/**

* 分页查询,默认查询数据总条数

*

* @param statementName

* 查询语句名称

* @param obj

* 查询参数对象

* @param page

* 分页参数

* @return

*/

@SuppressWarnings("unchecked")

public List queryForList(String statementName, Object obj, QueryPageDTO page) {

return queryForList(statementName, obj, page, true);

}

/**

* 分页查询

*

* @param statementName

* 查询语句名称

* @param obj

* 查询参数对象

* @param page

* 分页参数

* @param queryAllCount

* 是否查询数据总条数,true:是,false:否(当page的allCount属性为0时才查询)

* @return

*/

@SuppressWarnings("unchecked")

public List queryForList(String statementName, Object obj,

QueryPageDTO page, boolean queryAllCount) {

try {

if (queryAllCount) {

page.setAllCount(0);// 使其每次都去查询数据总条数

}

return getSqlMapClientTemplate().getSqlMapClient().queryForList(

statementName, obj, page);

} catch (SQLException e) {

log.error(e);

return null;

}

}

/** 以下方法 0506 新增 cxj,为了在访问数据库出现异常的情况下能够向NMS告警* */

public Object insert(String statementName, Object parameterObject) {

try {

return getSqlMapClientTemplate().insert(statementName,

parameterObject);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return null;

//throw new DataAccessException();

}

}

public int update(String statementName, Object parameterObject) {

try {

return getSqlMapClientTemplate().update(statementName,

parameterObject);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return 0;

//throw new DataAccessException();

}

}

public Object queryForObject(String statementName) {

try {

return getSqlMapClientTemplate().queryForObject(statementName);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return null;

//throw new DataAccessException();

}

}

public Object queryForObject(String statementName, Object parameterObject) {

try {

return getSqlMapClientTemplate().queryForObject(statementName,

parameterObject);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return null;

//throw new DataAccessException();

}

}

@SuppressWarnings("unchecked")

public List queryForList(String statementName) {

try {

return getSqlMapClientTemplate().queryForList(statementName);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return null;

//throw new DataAccessException();

}

}

@SuppressWarnings("unchecked")

public List queryForList(String statementName, Object parameterObject) {

try {

return getSqlMapClientTemplate().queryForList(statementName,

parameterObject);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return null;

//throw new DataAccessException();

}

}

@SuppressWarnings("unchecked")

public Map<Object, Object> queryForMap(String statementName,

Object parameterObject, String keyProperty, String valueProperty) {

try {

return getSqlMapClientTemplate().queryForMap(statementName,

parameterObject, keyProperty, valueProperty);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return null;

//throw new DataAccessException();

}

}

public int delete(String statementName, Object parameterObject) {

try {

return getSqlMapClientTemplate().delete(statementName,

parameterObject);

} catch (Exception e) {

//SnmpTrapTools.accessDBError();

log.error(e);

return 0;

//throw new DataAccessException();

}

}

}

package com.coship.report.util;

import java.sql.Timestamp;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.logging.Level;

import java.util.logging.Logger;

/**

*

* @author

*

*/

public final class DateUtil {

private static Calendar cal = Calendar.getInstance();

private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

private static SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");

private static final String dateRegex = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))
(20|21|22|23|[0-1]?\\d):[0-5]?\\d:[0-5]?\\d$";

private static final String timeRegex = "([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9])";

/**

*

* @param dateStr 日期字符串 yyyyMMddHHmmss

* @return Date 日期类型

*/

public static String format(Date date) {

String dateStr = null;

try {

SimpleDateFormat sfTemp = new SimpleDateFormat("yyyyMMddHHmmss");

dateStr = sfTemp.format(date);

return dateStr;

} catch (Exception e) {

e.printStackTrace();

}

return dateStr;

}

/**

*

* @param dateStr 日期字符串 0000-00-00 00:00:00

* @return Date 日期类型

*/

public static Date format(String dateStr) {

java.util.Date dd = null;

try {

String compare = "yy-MM-dd HH:mm:ss";

if (null != dateStr && dateStr.length() == compare.length()) {

dateStr = "20" + dateStr;

}

dd = sf.parse(dateStr);

System.out.println(dd.toString());

} catch (Exception e) {

e.printStackTrace();

}

return dd;

}

/**

*

* @param dateStr 日期字符串 0000-00-00

* @return Date 日期类型

*/

public static Date sdFormat(String dateStr) {

java.util.Date dd = null;

try {

String compare = "yy-MM-dd";

if (null != dateStr && dateStr.length() == compare.length()) {

dateStr = "20" + dateStr;

}

dd = sdFormat.parse(dateStr);

} catch (Exception e) {

e.printStackTrace();

}

return dd;

}

public static Date getSystemDate() {

return new Date();

}

public static Timestamp getSystemTime() {

Date currentDate = new Date();

return new Timestamp(currentDate.getTime());

}

public static String getSystemTimeStr() {

return sf.format(new Date());

}

public static String getSystemDateStr() {

return sdFormat.format(new Date());

}

public static int getDays(Date date1, Date date2) {

if (date1 == null || date2 == null) {

return 0;

}

int days = 0;

cal = Calendar.getInstance();

cal = Calendar.getInstance();

cal.setTime(date2);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.HOUR_OF_DAY, 0);

date2 = cal.getTime();

cal.setTime(date1);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.HOUR_OF_DAY, 0);

if (date1.before(date2)) {

while (date2.after(cal.getTime())) {

cal.add(Calendar.DAY_OF_MONTH, 1);

days++;

}

} else {

while (date2.before(cal.getTime())) {

cal.add(Calendar.DAY_OF_MONTH, -1);

days--;

}

}

return days;

}

public static String formatter(Date date) {

return sf.format(date);

}

public static String sdFormatter(Date date) {

return sdFormat.format(date);

}

/**

* 计算2个日期之间的间隔天数,startDate和endDate的时间格式是yyyy-MM-dd

*

* @param startDate

* @param endDate

* @return

*/

public static int getIntervalDays(String startDate, String endDate) {

int intervalDays = 0;

// startDateTemp和endDateTemp的时间格式是yyyyMMdd

String startDateTemp = startDate.substring(0, 4) + startDate.substring(5, 7) + startDate.substring(8);

String endDateTemp = endDate.substring(0, 4) + endDate.substring(5, 7) + endDate.substring(8);

SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMMdd");

Date date1 = new Date();

Date date2 = new Date();

try {

date1 = formatDate.parse(startDateTemp);

date2 = formatDate.parse(endDateTemp);

} catch (Exception e) {

e.printStackTrace();

}

try {

long len = date2.getTime() - date1.getTime();

intervalDays = (int) (len / (24 * 60 * 60 * 1000));

} catch (Exception e) {

e.printStackTrace();

}

return intervalDays;

}

/**

* 计算2个日期之间的间隔天数,startDate和endDate的时间格式是yyyy-MM-dd

*

* @param startDate

* @param endDate

* @return

*/

public static int getIntervalDays(Date startDate, Date endDate) {

int intervalDays = 0;

try {

if (startDate.after(endDate)) {

Date temp = endDate;

endDate = startDate;

startDate = temp;

}

long len = endDate.getTime() - startDate.getTime();

intervalDays = (int) (len / (24 * 60 * 60 * 1000));

} catch (Exception e) {

e.printStackTrace();

}

return intervalDays;

}

/**

* 计算一个日期N天之前的日期

*

* @param intervalDays

* @return

*/

public static int getTodayBefore(String intervalDays) {

Calendar calendar = Calendar.getInstance();

calendar.add(Calendar.DATE, Integer.parseInt("-" + intervalDays));

Date date = calendar.getTime();

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

String dayBefore = format.format(date);

return Integer.parseInt(dayBefore);

}

/**

* 计算一个日期N天之后的日期

*

* @param intervalDays

* @return

*/

public static int getTodayAfter(String intervalDays) {

Calendar calendar = Calendar.getInstance();

calendar.add(Calendar.DATE, Integer.parseInt(intervalDays));

Date date = calendar.getTime();

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

String dayAfter = format.format(date);

return Integer.parseInt(dayAfter);

}

/**

* yyyy-MM-dd HH:mm:ss 返回时间的 yyyy-MM-dd

*

* @param startDate

* @param endDate

* @return

*/

public static String getDayString(Date date) {

try {

String dateStr = formatter(date);

dateStr = dateStr.substring(0, 10);

return dateStr;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* yyyy-MM-dd HH:mm:ss 返回时间的 HH:mm:ss

*

* @param startDate

* @param endDate

* @return

*/

public static String getTimeString(Date date) {

try {

String dateStr = formatter(date);

dateStr = dateStr.substring(11, 19);

return dateStr;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 计算一个日期N天之后的日期

*

* @param intervalDays

* @return

*/

public static String getTodayAfter(int intervalDays) {

Calendar calendar = Calendar.getInstance();

calendar.add(Calendar.DATE, intervalDays);

Date date = calendar.getTime();

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

String dayAfter = format.format(date);

return dayAfter;

}

/**

*

* @param time

* @return

*/

public static String getDayString(long time) {

String timePattren = "yyyyMMdd";

Date date = new Date(time);

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timePattren);

return simpleDateFormat.format(date);

}

/**

*

* @param time

* @return

*/

public static String getTimeString(long time) {

String timePattren = "yyyyMMddHHmmss";

Date date = new Date(time);

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timePattren);

return simpleDateFormat.format(date);

}

/**

* 获取时间的long型,精确到秒

*

* @param intervalDays

* @return

*/

public static long getDateLong(Date date) {

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

return calendar.getTimeInMillis() / 1000;

}

/**

* 获得固定格式的当前时间

*

* @return

*/

public static final String getCurrentTime(String timePattern) {

// String timePattren = "yyyyMMddHHmms";

SimpleDateFormat dfmt = new SimpleDateFormat(timePattern);

return dfmt.format(new Date());

}

/**

* 获取某一时刻的下一天时刻

*

* @param intervalDays

* @return

*/

public static Date getNextDate(Date date) {

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

long dateLong = calendar.getTimeInMillis();

Date nextDate = new Date(dateLong + (1000 * 60 * 60 * 24));

return nextDate;

}

/**

* 获取某一时刻的上一天时刻

*

* @param intervalDays

* @return

*/

public static Date getPreviousDate(Date date){

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

long dateLong = calendar.getTimeInMillis();

Date nextDate = new Date(dateLong - (1000 * 60 * 60 * 24));

return nextDate;

}

/**

* 获取某一时刻偏移量时刻,单位是天。当天以后用正整数,当前以前用负整数

*

* @param intervalDays

* @return

*/

public static Date getOffsetDayDate(Date date, int offset){

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

long dateLong = calendar.getTimeInMillis();

Date nextDate = new Date(dateLong + (offset*1000 * 60 * 60 * 24));

return nextDate;

}

/**

* Calendar转换为XMLGregorianCalendar

*

* @param calendar

* @return XMLGregorianCalendar

*/

// public static XMLGregorianCalendar convert(Calendar calendar) {

// XMLGregorianCalendar xmlcalendar = new XMLGregorianCalendarImpl();

// xmlcalendar.setYear(calendar.get(Calendar.YEAR));

// xmlcalendar.setMonth(calendar.get(Calendar.MONTH) + 1);

// xmlcalendar.setDay(calendar.get(Calendar.DAY_OF_MONTH));

// xmlcalendar.setHour(calendar.get(Calendar.HOUR_OF_DAY));

// xmlcalendar.setMinute(calendar.get(Calendar.MINUTE));

// xmlcalendar.setSecond(calendar.get(Calendar.SECOND));

// xmlcalendar.setMillisecond(calendar.get(Calendar.MILLISECOND));

// xmlcalendar.setTimezone(calendar.get(Calendar.ZONE_OFFSET) / 60000);

// return xmlcalendar;

// }

//Exception:

public static boolean isMatchDateFormat(String dateStr) {

if (StringUtil.isEmpty(dateStr)) {

return false;

}

if (dateStr.matches(dateRegex)) {

return true;

} else {

return false;

}

}

public static boolean isMatchTimeFormat(String timeStr) {

if (StringUtil.isEmpty(timeStr)) {

return false;

}

if (timeStr.matches(timeRegex)) {

return true;

} else {

return false;

}

}

public static void main(String[] args) throws ParseException {

// Date date1 = DateUtil.format("2006-08-08 00:02:02");

// Date date2 = DateUtil.format("2006-08-08 00:02:02");

// Date date3 = DateUtil.sdFormat("2006-08-18");

// System.out.println("dddd==" + date3);

// System.out.println(getDays(date1, date2));

// System.out.println("getSystemTimeStr=" + getSystemTimeStr());

// System.out.println("getSystemDateStr=" + getSystemDateStr());

// System.out.println("" + DateUtil.getIntervalDays(date1, date2));

// System.out.println("" + DateUtil.getDayString(date2));

// System.out.println("" + DateUtil.getTimeString(date2));

// System.out.println(DateUtil.format(new Date()));

// if (isMatchDateFormat("2008-02-29 08:55:02")) {

// System.out.println("Legal date format");

// } else {

// System.out.println("Illegal date format");

// }

//

// if (isMatchTimeFormat("1:01:60")) {

// System.out.println("Legal time format");

// } else {

// System.out.println("Illegal time format");

// }

// String str = "2008-12-19T07:43:08Z";

// Date date = formatUTC(str);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String cc = sdf.format(new Date());

}

/**

* 按照传入的时间周期,截取时间数据

* @param date

* @param interval

* @return

*/

public static Date truncDate(Date date,long interval){

if(date==null) return null;

if(interval==0) return date;

return new Date(date.getTime()/interval*interval);

}

/**

* 格林尼治时间转换成Date

*/

public static Date formatUTC(String utcStr){

if(utcStr==null) return null;

try {

utcStr = utcStr.replace("Z", " UTC");

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");

Date date = sdf.parse(utcStr);

//-8*60*60*1000

return new Date(date.getTime());

} catch (Exception ex) {

ex.printStackTrace();

return null;

}

}

public static String createUTC(Date date){

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");

String cc = sdf.format(new Date(date.getTime()-8*60*60*1000));

return cc.substring(0,19)+"Z";

}

}

package com.coship.report.util;

import java.io.BufferedInputStream;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.StringTokenizer;

import org.apache.log4j.Logger;

/**

* add by

* **/

public class FileTool {

private Logger log=Logger.getLogger(FileTool.class);

private String message;

public FileTool() {

}

/**

* 读取文本文件内容

* @param filePathAndName 带有完整绝对路径的文件名

* @param encoding 文本文件打开的编码方式

* @return 返回文本文件的内容

*/

public String readTxt(String filePathAndName,String encoding) throws IOException{

encoding = encoding.trim();

StringBuffer str = new StringBuffer("");

String st = "";

try{

FileInputStream fs = new FileInputStream(filePathAndName);

InputStreamReader isr;

if(encoding.equals("")){

isr = new InputStreamReader(fs);

}else{

isr = new InputStreamReader(fs,encoding);

}

BufferedReader br = new BufferedReader(isr);

try{

String data = "";

while((data = br.readLine())!=null){

str.append(data+"\r\n ");

}

}catch(Exception e){

str.append(e.toString());

}

st = str.toString();

}catch(IOException es){

st = "";

}

return st;

}

/**

* 采用BufferedInputStream方式读取文件行数

*

* @param filename

* @return

* @throws IOException

*/

public int readLineCount(String filename) throws IOException {

InputStream is = new BufferedInputStream(new FileInputStream(filename));

byte[] c = new byte[1024];

int count = 0;

int readChars = 0;

while ((readChars = is.read(c)) != -1) {

for (int i = 0; i < readChars; ++i) {

if (c[i] == '\n')

++count;

}

}

is.close();

return count;

}

/**

* 读取文本文件内容

* @param filePathAndName 带有完整绝对路径的文件名

* @param encoding 文本文件打开的编码方式

* @return 返回文本文件的内容

*/

public InputStream readTxt(String filePathAndName) throws IOException{

StringBuffer str = new StringBuffer("");

String st = "";

FileInputStream fs = new FileInputStream(filePathAndName);

return fs;

}

/**

* 新建目录

* @param folderPath 目录

* @return 返回目录创建后的路径

*/

public String createFolder(String folderPath) {

String txt = folderPath;

try {

java.io.File myFilePath = new java.io.File(txt);

txt = folderPath;

if (!myFilePath.exists()) {

myFilePath.mkdir();

}

}

catch (Exception e) {

message = "创建目录操作出错";

}

return txt;

}

/**

* 多级目录创建

* @param folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:myf

* @param paths 无限级目录参数,各级目录以单数线区分 例如 a|b|c

* @return 返回创建文件后的路径 例如 c:myfac

*/

public String createFolders(String folderPath, String paths){

String txts = folderPath;

try{

String txt;

txts = folderPath;

StringTokenizer st = new StringTokenizer(paths,"|");

for(int i=0; st.hasMoreTokens(); i++){

txt = st.nextToken().trim();

if(txts.lastIndexOf("/")!=-1){

txts = createFolder(txts+txt);

}else{

txts = createFolder(txts+txt+"/");

}

}

log.info("创建目录"+folderPath+"成功");

}catch(Exception e){

message = "创建目录操作出错!";

}

return txts;

}

/**

* 新建文件

* @param filePathAndName 文本文件完整绝对路径及文件名

* @param fileContent 文本文件内容

* @return

*/

public void createFile(String filePathAndName, String fileContent) {

try {

String filePath = filePathAndName;

filePath = filePath.toString();

File myFilePath = new File(filePath);

if (!myFilePath.exists()) {

log.info(filePathAndName+"不存在,创建文件成功");

myFilePath.createNewFile();

}

FileWriter resultFile = new FileWriter(myFilePath);

PrintWriter myFile = new PrintWriter(resultFile);

String strContent = fileContent;

myFile.println(strContent);

myFile.close();

resultFile.close();

}

catch (Exception e) {

e.printStackTrace();

message = "创建文件操作出错";

}

}

/**

* 有编码方式的文件创建

* @param filePathAndName 文本文件完整绝对路径及文件名

* @param fileContent 文本文件内容

* @param encoding 编码方式 例如 GBK 或者 UTF-8

* @return

*/

public void createFile(String filePathAndName, String fileContent, String encoding) {

try {

String filePath = filePathAndName;

filePath = filePath.toString();

File myFilePath = new File(filePath);

if (!myFilePath.exists()) {

myFilePath.createNewFile();

}

/*PrintWriter myFile = new PrintWriter(myFilePath);

String strContent = fileContent;

myFile.println(strContent);

myFile.close();*/

}

catch (Exception e) {

message = "创建文件操作出错";

e.printStackTrace();

}

}

/**

* 删除文件

* @param filePathAndName 文本文件完整绝对路径及文件名

* @return Boolean 成功删除返回true遭遇异常返回false

*/

public boolean delFile(String filePathAndName) {

boolean bea = false;

try {

String filePath = filePathAndName;

File myDelFile = new File(filePath);

if(myDelFile.exists()){

myDelFile.delete();

bea = true;

}else{

bea = false;

message = (filePathAndName+"<br>删除文件操作出错");

}

}

catch (Exception e) {

message = e.toString();

}

return bea;

}

/**

* 删除文件夹

* @param folderPath 文件夹完整绝对路径

* @return

*/

public void delFolder(String folderPath) {

try {

delAllFile(folderPath); //删除完里面所有内容

String filePath = folderPath;

filePath = filePath.toString();

java.io.File myFilePath = new java.io.File(filePath);

myFilePath.delete(); //删除空文件夹

}

catch (Exception e) {

message = ("删除文件夹操作出错");

}

}

/**

* 删除指定文件夹下所有文件

* @param path 文件夹完整绝对路径

* @return

* @return

*/

private static Integer jj=0;

public boolean delAllFile(String path) {

boolean bea = false;

File file = new File(path);

if (!file.exists()) {

return bea;

}

if (!file.isDirectory()) {

return bea;

}

jj++;

String[] tempList = file.list();

File temp = null;

for (int i = 0; i < tempList.length; i++) {

if (path.endsWith(File.separator)) {

temp = new File(path + tempList);

}else{

temp = new File(path + File.separator + tempList);

}

if (temp.isFile()) {

temp.delete();

}

if (temp.isDirectory()) {

delAllFile(path+"/"+ tempList);//先删除文件夹里面的文件

delFolder(path+"/"+ tempList);//再删除空文件夹

bea = true;

}

}

System.out.println(jj);

return bea;

}

/**

* 复制单个文件

* @param oldPathFile 准备复制的文件源

* @param newPathFile 拷贝到新绝对路径带文件名

* @return

*/

public void copyFile(String oldPathFile, String newPathFile) {

try {

int bytesum = 0;

int byteread = 0;

File oldfile = new File(oldPathFile);

if (oldfile.exists()) { //文件存在时

InputStream inStream = new FileInputStream(oldPathFile); //读入原文件

FileOutputStream fs = new FileOutputStream(newPathFile);

byte[] buffer = new byte[1444];

while((byteread = inStream.read(buffer)) != -1){

bytesum += byteread; //字节数 文件大小

//System.out.println(bytesum);

fs.write(buffer, 0, byteread);

}

inStream.close();

}

}catch (Exception e) {

message = ("复制单个文件操作出错");

}

}

/**

* 复制整个文件夹的内容

* @param oldPath 准备拷贝的目录

* @param newPath 指定绝对路径的新目录

* @return

*/

public void copyFolder(String oldPath, String newPath) {

try {

new File(newPath).mkdirs(); //如果文件夹不存在 则建立新文件夹

File a=new File(oldPath);

String[] file=a.list();

File temp=null;

for (int i = 0; i < file.length; i++) {

if(oldPath.endsWith(File.separator)){

temp=new File(oldPath+file[i]);

}else{

temp=new File(oldPath+File.separator+file[i]);

}

if(temp.isFile()){

FileInputStream input = new FileInputStream(temp);

FileOutputStream output = new FileOutputStream(newPath + "/" +

(temp.getName()).toString());

byte[] b = new byte[1024 * 5];

int len;

while ((len = input.read(b)) != -1) {

output.write(b, 0, len);

}

output.flush();

output.close();

input.close();

}

if(temp.isDirectory()){//如果是子文件夹

copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);

}

}

}catch (Exception e) {

message = "复制整个文件夹内容操作出错";

}

}

/**

* 移动文件

* @param oldPath

* @param newPath

* @return

*/

public void moveFile(String oldPath, String newPath) {

copyFile(oldPath, newPath);

delFile(oldPath);

}

/**

* 移动目录

* @param oldPath

* @param newPath

* @return

*/

public void moveFolder(String oldPath, String newPath) {

copyFolder(oldPath, newPath);

delFolder(oldPath);

}

public String getMessage(){

return this.message;

}

public static void main(String[] args){

try{

FileTool ft = new FileTool();

ft.delAllFile("E:\\JBossESB");

}catch(Exception ex){

ex.printStackTrace();

}

}

}

package com.coship.report.util;

import java.io.Serializable;

import com.ibatis.sqlmap.IQueryPage;

/**

* 分页查询对象

*/

public class QueryPageDTO implements IQueryPage, Serializable {

private static final long serialVersionUID = 8347220722610858942L;

// 起始位置

int beginIndex = 1;

// 终止位置

int endIndex = 10;

int allCount = 0;

String database;

public int getBeginIndex() {

return beginIndex;

}

public void setBeginIndex(int beginIndex) {

this.beginIndex = beginIndex;

}

public int getEndIndex() {

return endIndex;

}

public void setEndIndex(int endIndex) {

this.endIndex = endIndex;

}

public int getAllCount() {

return allCount;

}

public void setAllCount(int allCount) {

this.allCount = allCount;

}

public String getDatabase() {

return database;

}

public void setDatabase(String arg0) {

if("MySQL".equals(arg0))

this.database = "mysql";

else {

this.database = "oracle";

}

}

}

/*

* StringUtils.java

*

* Created on 2007-11-14, 15:59:29

*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package com.coship.report.util;

import java.io.ByteArrayOutputStream;

import java.io.PrintWriter;

import java.io.UnsupportedEncodingException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.NoSuchElementException;

import java.util.StringTokenizer;

//import com.sun.org.apache.xerces.internal.impl.xpath.regex.RegularExpression;

/**

*

* @author administrator

*/

public final class StringUtil {

/**

* 将对象ToString

* @param c

* @return

*/

public static String toString(Object c){

if(c==null){

return "";

}

else{

return c.toString();

}

}

/**

* 将byte数组转换为表示16进制值的字符串,

* 如:byte[]{8,18}转换为:0813,

* 和public static byte[] hexStr2ByteArr(String strIn)

* 互为可逆的转换过程

* @param arrB 需要转换的byte数组

* @return 转换后的字符串

* @throws Exception 本方法不处理任何异常,所有异常全部抛出

* @author <a href="mailto:zhangji@aspire-tech.com">ZhangJi</a>

*/

public static String byteArr2HexStr(byte[] arrB)

throws Exception {

int iLen = arrB.length;

//每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍

StringBuffer sb = new StringBuffer(iLen * 2);

for (int i = 0; i < iLen; i++) {

int intTmp = arrB[i];

//把负数转换为正数

while (intTmp < 0) {

intTmp = intTmp + 256;

}

//小于0F的数需要在前面补0

if (intTmp < 16) {

sb.append("0");

}

sb.append(Integer.toString(intTmp, 16));

}

return sb.toString();

}

/**

* 将表示16进制值的字符串转换为byte数组,

* 和public static String byteArr2HexStr(byte[] arrB)

* 互为可逆的转换过程

* @param strIn 需要转换的字符串

* @return 转换后的byte数组

* @throws Exception 本方法不处理任何异常,所有异常全部抛出

* @author <a href="mailto:zhangji@aspire-tech.com">ZhangJi</a>

*/

public static byte[] hexStr2ByteArr(String strIn)

throws Exception {

byte[] arrB = strIn.getBytes();

int iLen = arrB.length;

//两个字符表示一个字节,所以字节数组长度是字符串长度除以2

byte[] arrOut = new byte[iLen / 2];

for (int i = 0; i < iLen; i = i + 2) {

String strTmp = new String(arrB, i, 2);

arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);

}

return arrOut;

}

/**

*@param str the string need to be parsed

*@param delim the delimiter to seperate

* created by YanFeng at 14/5/2003

*/

public static String[] parseToArray(String str, String delim) {

ArrayList arr = new ArrayList();

StringTokenizer st = new StringTokenizer(str, delim);

while (st.hasMoreTokens()) {

arr.add(st.nextToken());

}

String[] ret = new String[arr.size()];

for (int i = 0; i < arr.size(); i++) {

ret[i] = (String) arr.get(i);

}

return ret;

}

/**

replace a old substring with rep in str

@param str the string need to be replaced

@param old the string need to be removed

@param rep the string to be inserted

@return string replaced

*/

public static String replace(String str, String old, String rep) {

if ((str == null) || (old == null) || (rep == null)) {//if one is null return ""

return "";

}

int index = str.indexOf(old);

if ((index < 0) || old.equals("")) { //if no old string found or nothing to replace,return the origin

return str;

}

StringBuffer strBuf = new StringBuffer(str);

while (index >= 0) { //found old part

strBuf.delete(index, index + old.length());

strBuf.insert(index, rep);

index = strBuf.toString().indexOf(old);

}

return strBuf.toString();

}

public static String replaceOnlyOnce(String str, String old, String rep) {

if ((old == null) || old.equals("")) {//if old is null or blank return the original string

return str;

}

if ((str == null) || str.equals("")) {//if str is null or blank return the original string

return str;

}

int leftIndex = str.indexOf(old);

if (leftIndex < 0) { //if no old string found so nothing to replace,return the origin

return str;

}

String leftStr = str.substring(0, leftIndex);

String rightStr = str.substring(leftIndex + old.length());

return leftStr + rep + rightStr;

}

/**

* get the string format of a date precise to millisecond

* @param date the input date

* @return the string

* created

*/

public static String getTimeString(Date date) {

String timePattren = "yyyyMMddHHmmssSSS";

return toString(date, timePattren);

}

/**

convert a date to string according to the format pattern

* @param date input date

* @param pattern format pattern

* @return the formated string

*/

public static String toString(Date date, String pattern) {

SimpleDateFormat fo = new SimpleDateFormat(pattern);

return fo.format(date);

}

/**

* Deal with null strings converting them to "" instead. It also

* invokes String.trim() on the output.

*

* @param foo A String.

* @return A String.

*/

public static final String makeString(String foo) {

return (foo == null ? "" : foo.trim());

}

/**

* Validates that the supplied string is neither <code>null</code>

* nor the empty string.

*

* @param foo The text to check.

* @return Whether valid.

*/

public static final boolean isValid(String foo) {

return (foo != null && foo.length() > 0);

}

/**

* Determine whether a (trimmed) string is empty

*

* @param foo The text to check.

* @return Whether empty.

*/

public static final boolean isEmpty(String foo) {

return (foo == null || foo.trim().length() == 0);

}

/**

* Returns the output of printStackTrace as a String.

*

* @param e A Throwable.

* @return A String.

*/

public static final String stackTrace(Throwable e) {

String foo = null;

try {

// And show the Error Screen.

ByteArrayOutputStream buf = new ByteArrayOutputStream();

e.printStackTrace(new PrintWriter(buf, true));

foo = buf.toString();

} catch (Exception f) {

// Do nothing.

}

return foo;

}

/**

* Returns the output of printStackTrace as a String.

*

* @param e A Throwable.

* @param addPre a boolean to add HTML <pre> tags around the stacktrace

* @return A String.

*/

public static final String stackTrace(Throwable e, boolean addPre) {

if (addPre) {

return "<pre>" + stackTrace(e) + "</pre>";

} else {

return stackTrace(e);

}

}

/**

* Compares two Strings, returns true if their values are the

* same.

*

* @param s1 The first string.

* @param s2 The second string.

* @return True if the values of both strings are the same.

*/

public static boolean equals(String s1, String s2) {

if (s1 == null) {

return (s2 == null);

} else if (s2 == null) {

// s1 is not null

return false;

} else {

return s1.equals(s2);

}

}

public static final int PPKEY_CLASSNAME = 0;

public static final int PPKEY_ID = 1;

public static final int PPKEY_PROPERTY = 2;

/**

* Takes a String of the form substring[substring]subtring and

* returns the 3 substrings

*

* @return a three element String array

*/

public static String[] parseObjectKey(String s) {

String[] p = new String[3];

StringTokenizer st = new StringTokenizer(s, "[]");

int count = st.countTokens();

if (count > 1) {

p[0] = st.nextToken();

p[1] = st.nextToken();

if (count == 3) {

p[2] = st.nextToken();

}

}

return p;

}

/**

* Remove Underscores from a string and replaces first

* Letters with Capitals. foo_bar becomes FooBar

*/

public static String removeUnderScores(String data) {

String temp = null;

StringBuffer out = new StringBuffer();

temp = data.toLowerCase();

StringTokenizer st = new StringTokenizer(temp, "_");

while (st.hasMoreTokens()) {

String element = (String) st.nextElement();

out.append(firstLetterCaps(element));

}

return out.toString();

}

/**

* Makes the first letter caps and leaves the rest as is.

*/

public static String firstLetterCaps(String data) {

StringBuffer sbuf = new StringBuffer(data.length());

sbuf.append(data.substring(0, 1).toUpperCase()).append(data.substring(1));

return sbuf.toString();

}

/**

* Makes the first letter lowercase and leaves the rest as is.

*/

public static String firstLetterLower(String data) {

StringBuffer sbuf = new StringBuffer(data.length());

sbuf.append(data.substring(0, 1).toLowerCase()).append(data.substring(1));

return sbuf.toString();

}

/**

* Splits the provided CSV text into a list.

*

* @param text The CSV list of values to split apart.

* @param separator The separator character.

* @return The list of values.

*/

public static String[] split(String text, String separator) {

StringTokenizer st = new StringTokenizer(text, separator);

String[] values = new String[st.countTokens()];

int pos = 0;

while (st.hasMoreTokens()) {

values[pos++] = st.nextToken();

}

return values;

}

/**

* Joins the elements of the provided array into a single string

* containing a list of CSV elements.

*

* @param list The list of values to join together.

* @param separator The separator character.

* @return The CSV text.

*/

public static String join(String[] list, String separator) {

StringBuffer csv = new StringBuffer();

for (int i = 0; i < list.length; i++) {

if (i > 0) {

csv.append(separator);

}

csv.append(list[i]);

}

return csv.toString();

}

/**

* Takes a block of text which might have long lines in it and wraps

* the long lines based on the supplied wrapColumn parameter. It was

* initially implemented for use by VelocityEmail. If there are tabs

* in inString, you are going to get results that are a bit strange,

* since tabs are a single character but are displayed as 4 or 8

* spaces. Remove the tabs.

*

* @param inString Text which is in need of word-wrapping.

* @param newline The characters that define a newline.

* @param wrapColumn The column to wrap the words at.

* @return The text with all the long lines word-wrapped.

*/

public static String wrapText(String inString, String newline,

int wrapColumn) {

StringTokenizer lineTokenizer = new StringTokenizer(

inString, newline, true);

StringBuffer stringBuffer = new StringBuffer();

while (lineTokenizer.hasMoreTokens()) {

try {

String nextLine = lineTokenizer.nextToken();

if (nextLine.length() > wrapColumn) {

// This line is long enough to be wrapped.

nextLine = wrapLine(nextLine, newline, wrapColumn);

}

stringBuffer.append(nextLine);

} catch (NoSuchElementException nsee) {

// thrown by nextToken(), but I don't know why it would

break;

}

}

return (stringBuffer.toString());

}

/**

* Wraps a single line of text. Called by wrapText(). I can't

* think of any good reason for exposing this to the public,

* since wrapText should always be used AFAIK.

*

* @param line A line which is in need of word-wrapping.

* @param newline The characters that define a newline.

* @param wrapColumn The column to wrap the words at.

* @return A line with newlines inserted.

*/

protected static String wrapLine(String line, String newline,

int wrapColumn) {

StringBuffer wrappedLine = new StringBuffer();

while (line.length() > wrapColumn) {

int spaceToWrapAt = line.lastIndexOf(' ', wrapColumn);

if (spaceToWrapAt >= 0) {

wrappedLine.append(line.substring(0, spaceToWrapAt));

wrappedLine.append(newline);

line = line.substring(spaceToWrapAt + 1);

} // This must be a really long word or URL. Pass it

// through unchanged even though it's longer than the

// wrapColumn would allow. This behavior could be

// dependent on a parameter for those situations when

// someone wants long words broken at line length.

else {

spaceToWrapAt = line.indexOf(' ', wrapColumn);

if (spaceToWrapAt >= 0) {

wrappedLine.append(line.substring(0, spaceToWrapAt));

wrappedLine.append(newline);

line = line.substring(spaceToWrapAt + 1);

} else {

wrappedLine.append(line);

line = "";

}

}

}

// Whatever is left in line is short enough to just pass through,

// just like a small small kidney stone

wrappedLine.append(line);

return wrappedLine.toString();

}

/**

* convert the ISO char encoding to GBK

* @param str the ISO encoding string

* @return the GBK encoding string

* created by yanfeng at 13/5/2003

* modified by yanfeng at14/7/2003

* for recursive invoke of this function in log.error()

* @CheckItem@ SELFBUG-yanfeng-20030714 可能产生循环调用

*/

public static String ISOtoGBK(String str) {

byte[] by = null;

try {

by = str.getBytes("ISO-8859-1");

} catch (UnsupportedEncodingException ex) {

ex.printStackTrace();

return str;

}

try {

String a = new String(by, "GBK");

return a;

} catch (UnsupportedEncodingException ex1) {

ex1.printStackTrace();

return str;

}

}

public static String formatRuleIp(String sourceIp) {

String objectIp = "";

if (sourceIp != null && !sourceIp.equals("") && sourceIp.length() > 0) {

String port = "";

int i = 0;

while (sourceIp.indexOf('.') != -1) {

port = sourceIp.substring(0, sourceIp.indexOf('.'));

sourceIp = sourceIp.substring(sourceIp.indexOf('.') + 1);

if (!port.equals("") && port.length() > 0) {

if (port.length() < 3) {

port = "0" + port;

}

if (port.length() < 3) {

port = "0" + port;

}

}

objectIp += port + ".";

if (sourceIp.indexOf('.') == -1) {

port = sourceIp;

if (port.length() < 3) {

port = "0" + port;

}

if (port.length() < 3) {

port = "0" + port;

}

objectIp += port;

}

i++;

if (objectIp.length() == 16) {

objectIp = objectIp.substring(0, objectIp.length() - 1);

}

if (i == 4) {

break;

}

}

}

return objectIp;

}

/**

* convert the GB2312 char encoding to UTF-8

* @param str the GB2312 encoding string

* @return the UTF-8 encoding string

*/

public static String GB2312toUTF(String str) {

byte[] by = null;

try {

by = str.getBytes("GB2312");

} catch (UnsupportedEncodingException ex) {

ex.printStackTrace();

return str;

}

try {

String a = new String(by, "UTF-8");

return a;

} catch (UnsupportedEncodingException ex1) {

ex1.printStackTrace();

return str;

}

}

/**

* convert the UTF-8 char encoding to GB2312

* @param str the UTF-8 encoding string

* @return the GB2312 encoding string

*/

public static String UTFtoGB2312(String str) {

byte[] by = null;

try {

by = str.getBytes("UTF-8");

} catch (UnsupportedEncodingException ex) {

ex.printStackTrace();

return str;

}

try {

String a = new String(by, "GB2312");

return a;

} catch (UnsupportedEncodingException ex1) {

ex1.printStackTrace();

return str;

}

}

/**

* trim the string even when it's null

* @param str the string need to be trimmed

* @return the trimmed string

*/

public static String trim(String str) {

if (str == null) {

return "";

}

return str.trim();

}

/**

* 判断str是否在strArr中

* @param str

* @param strArr

* @return true:str在strArr中出现,;false otherwise.

*/

public static boolean stringInArray(String str, String[] strArr) {

for (int i = 0; i < strArr.length; i++) {

if (str.equals(strArr[i])) {

return true;

}

}

return false;

}

/**

* 将带有格式的字符串转换成HTML方式

* @param origine

* @return

*/

public static String convert2Html(String origine) {

String outStr = null;

if (origine != null) {

String tmp = StringUtil.replace(origine, ">", ">");

String tmp2 = StringUtil.replace(tmp, "<", "<");

String tmp3 = StringUtil.replace(tmp2, " ", " ");

String tmp4 = StringUtil.replace(tmp3, "\r\n", "<br>");

outStr = tmp4;

} else {

outStr = "";

}

return outStr;

}

public static String getTrimStr(String str) {

if (null != str) {

char[] ch = str.toCharArray();

StringBuffer sb = new StringBuffer(ch.length);

for (int i = 0; i < ch.length; i++) {

if (ch[i] != ' ') {

sb.append(ch[i]);

}

}

return sb.toString();

}

return null;

}

/**

* 校验密码合法性

* @rule 密码只能由“0-9”、“a-z”、“A-Z”、“!”、“?”、“_”组成

* @param pwd

* @return true 合法;false 不合法

*/

public static boolean checkPwd(String pwd) {

if (pwd != null && !"".equals(pwd.trim())) {

char[] charArray = pwd.toCharArray();

for (int i = 0; i < charArray.length; i++) {

char c = charArray[i];

if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >=

'A' && c <= 'Z') || (c == '!') || (c == '?') || (c ==

'_'))) {

return false;

}

}

return true;

}

return false;

}

/**

* 将str插入原字符串的flag前或后

* @param src = 源字符串

* @param str = 插入字符串

* @param flag = 插入标志

* @param boa = true:插入flag前;false:插入flag后

* @retrun 插入后的字符串

*/

public static String insertStr(String src, String flag, String str, Boolean boa) {

if (!src.contains(flag))//源串中没有插入标志

{

return src;

}

if (boa)//before flag

{

} else //after flag

{

}

return null;

}

/**

* Change digital String to Integer

*/

public static Integer str2Integer(String digitalStr) {

if (isEmpty(digitalStr)) {

return null;

}

Integer integer = null;

try {

integer = Integer.parseInt(digitalStr);

} catch (Exception e) {

e.getStackTrace();

System.out.println("Illegal digital string!");

}

return integer;

}

/*

* Check port

*/

public static boolean checkStrPort(String strPort) {

Integer port = 0;

try {

port = str2Integer(strPort);

if(port==null) return false;

} catch (Exception ex) {

return false;

}

if (port > 65535 || port < 0) {

return false;

}

return true;

}

public static void substring(String txt) {

if (txt.contains("[") && txt.contains("]")) {

String command = txt.substring(0, txt.indexOf("["));

System.out.println("command=" + command);

String args = txt.substring(txt.indexOf("[") + 1, txt.indexOf("]"));

System.out.println("args=" + args);

String[] array = args.split("-");

for (String str : array) {

System.out.println("str=" + str);

}

}

}

/**

* 在左边不足给定长度的

* @param oldStr

* @param length

* @param c

* @return

*/

public static String lpad(String oldStr,int length,char c){

if(oldStr==null||oldStr.length()>length) return oldStr;

String e = oldStr;

while(e.length()<length){

e=c+e;

}

return e;

}

/**

*

* @param str

* @param length

* @param c

* @return

*/

public static String makeRegularString(String str,int length,char c){

if(str==null) return str;

char[] cArray = str.toCharArray();

char[] rArray = new char[cArray.length+cArray.length/length];

int j=1;

int k=0;

for(int i=cArray.length-1;i>=0;i--){

if(j%length==0&&i!=0){

rArray[k]=cArray[i];

k++;

rArray[k]=c;

k++;

}else{

rArray[k]=cArray[i];

k++;

}

j++;

}

String ccc="";

for(int i=rArray.length-1;i>=0;i--){

ccc+=rArray[i];

}

return ccc;

}

public static void main(String[] args) {

System.out.println(makeRegularString("12345678444",2,'.'));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: