论坛首页 编程语言技术论坛

java从FTP获取文件,解压缩,读取文件,拷贝文件,删除文件等一系列功能

浏览 5508 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-09-15  
//往ftp上上传文件
public static void upFile(String server,String username,String password,String ftpurls,String localurls) {
String ftpurl=ftpurls.substring(0,ftpurls.lastIndexOf("/")+1);//截取出ftp上的路径
String filename=ftpurls.substring(ftpurls.lastIndexOf("/")+1);//截取出文件名
String localurl=localurls+"/"+filename;//再拼凑出本地路径
try {
FtpClient ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(username, password);
if (ftpurl.length() != 0){
ftpClient.cd(ftpurl);
}
ftpClient.binary();
TelnetOutputStream os = ftpClient.put(filename);
File file_in = new File(localurl);
FileInputStream is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
is.close();
os.close();
ftpClient.closeServer();

}catch(Exception e){}
}

//从ftp上下载文件
public void downLoadFile(String server,String username,String password,String ftpurls,String localurls) {

String ftpurl=ftpurls.substring(0,ftpurls.lastIndexOf("/")+1);//截取出ftp上的路径
String filename=ftpurls.substring(ftpurls.lastIndexOf("/")+1);//截取出文件名
String localurl=localurls+filename;//再拼凑出本地路径
try {
FtpClient ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(username, password);
if (ftpurl.length() != 0){
ftpClient.cd(ftpurl);
}
ftpClient.binary();
TelnetInputStream is = ftpClient.get(filename);
////cs_vip_card.txt.Z 不是file
File file_out = new File(localurl);
file_out.createNewFile();

FileOutputStream os = new FileOutputStream(file_out);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
is.close();
os.close();
ftpClient.closeServer();
} catch (Exception ex) {
LOG.ADMININFO("downLoadFile从FTP获取文件失败:"+ex.getMessage());
ex.printStackTrace();
//JOptionPane.showMessageDialog(null,"很报谦!ftp连接失败,所需文件暂时不能下载!!");
}

}


/**
* 拷贝文件到目标目录并删除源文件
* @param srcFilePath   d:/abc/mytest.txt
* @param destDirPath   d:/abc_bak/
*/
public void copyfileAndDel(String srcFilePath,String destDirPath){
try{
File file = new File(srcFilePath);
String fileName = file.getName();
String destFileName = destDirPath + File.separator+ fileName+"."+System.currentTimeMillis();
LOG.ADMININFO("copyfileAndDel#############destFileName:"+destFileName+"##################|destDirPath:"+destDirPath+"|File.separator:"+File.separator+"|fileName:"+fileName);
tocopyFile(srcFilePath, destFileName);
//删除源文件
  this.deleteFile(srcFilePath);
}catch(Exception e){
System.out.println("没有这个文件");
return;
}
}
/**
    * 删除指定的文件
    * @param filePath
    */
public void deleteFile(String filePath){
   File file = new File(filePath);
   boolean flag = file.delete();
   System.out.println("删除文件:"+filePath);
}
public void tocopyFile(String srcFilePath, String desFilePath){
        int byteread = 0;
        InputStream in = null;
        FileOutputStream out = null;
        try{
            in = new FileInputStream(srcFilePath);
            out = new FileOutputStream(desFilePath);
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        try{
            while((byteread = in.read(buffer)) != -1){
                out.write(buffer, 0, byteread);
            }
            in.close();
            out.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
/** 定时执行的
* 从FTP下载文件
* @param args
*/
public void getFileFromFTP(String ... args) throws AppException{
Properties p = getProperties();
String ftpIDSIP = p.getProperty("ftpIDSIP");
String ftpUsername = p.getProperty("ftpUsername");
String ftpPassword = p.getProperty("ftpPassword");
String ftpPath = p.getProperty("ftpPath");
String localPath = p.getProperty("localPath");
String localPathbak = p.getProperty("localPathbak");
//拼接一个ftp中文件的路径  /date/20120815/cs_vip_card.txt
String date = "";
if(args != null && args.length == 1){
date = CommonFunction.getPrevDay(args[0], 1);
}else if(args != null && args.length == 2){
date = CommonFunction.getPrevDay(args[0], Integer.parseInt(args[1]));
}else{
date = CommonFunction.getPrevDay(CommonFunction.getLocalDate(), 1);
}
ftpPath = ftpPath +"/"+date +"/cs_vip_card.txt.Z";
//String localurl=localurls+filename;//再拼凑出本地路径
try {
downLoadFile(ftpIDSIP,ftpUsername,ftpPassword,ftpPath,localPath);
LOG.ADMININFO("downLoadFile下载文件完成########################"+CommonFunction.getLocalTime14());
} catch (Exception e) {
LOG.ADMININFO("downLoadFile下载文件错误:"+CommonFunction.getLocalTime14());
e.printStackTrace();
}
try {
upzipFile(localPath);
LOG.ADMININFO("upzipFile解压缩完成########################"+CommonFunction.getLocalTime14());
} catch (Exception e) {
LOG.ADMININFO("upzipFile解压缩文件错误:"+CommonFunction.getLocalTime14());
e.printStackTrace();
}
try {
localPath = localPath+"/cs_vip_card.txt";
GetInfo(localPath);
LOG.ADMININFO("GetInfo获取文件数据并保存到AMSVIPINFO表完成########################"+CommonFunction.getLocalTime14());
} catch (Exception e) {
LOG.ADMININFO("GetInfo获取文件数据并保存到AMSVIPINFO表信息错误:"+CommonFunction.getLocalTime14());
e.printStackTrace();
}
try {
copyfileAndDel(localPath, localPathbak);
LOG.ADMININFO("copyfileAndDel复制文件到备份目录并且删除本地源文件完成#################################"+CommonFunction.getLocalTime14());
} catch (Exception e) {
LOG.ADMININFO("copyfileAndDel复制文件到备份目录并且删除本地源文件信息错误:"+CommonFunction.getLocalTime14());
e.printStackTrace();
}
}
/****************/
//localPath=/cpic/bqgpspad/java/domains/
public void upzipFile(String localPath) throws Exception{
String command = "uncompress "+localPath+"cs_vip_card.txt.Z";
Process process = Runtime.getRuntime().exec(command);
InputStream is = process.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String buff = "";
StringBuffer sb = new StringBuffer();
while((buff =in.readLine())!=null){
sb.append(buff);
sb.append("\n");
}
}



/*****读取文件***********************/
private String GetTxtCode(String path){ // 获取text文件编码
String code = "";
code = "gb2312";
try {
InputStream is = new FileInputStream(path);
byte[] head = new byte[3];
try {
is.read(head);
if (head[0] == -1 && head[1] == -2)
code = "UTF-16";
if (head[0] == -2 && head[1] == -1)
code = "Unicode";
if (head[0] == -17 && head[1] == -69 && head[2] == -65)
code = "UTF-8";
} catch (IOException e) {
e.printStackTrace();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
}
return code;
}
public int GetLines(String fileName) throws IOException {// 获取文件行数以便建立数组维度

FileReader in = new FileReader(fileName);
LineNumberReader reader = new LineNumberReader(in);
String strLine = reader.readLine();
int totalLines = 0;
while (strLine != null) {
totalLines++;
strLine = reader.readLine();
}
reader.close();
in.close();
return totalLines;
}

// /然后读取文件信息,这里读取的文件每行四个信息块,以制表符为分隔符:

public void GetInfo(String path) throws IOException,FileNotFoundException {
int Lines = this.GetLines(path);
System.out.println("Txt File Lines:" + Lines);
String[][] s = new String[Lines][4];
File f = new File(path);
String code = GetTxtCode(path);
System.out.println("Txt File Code:" + code);
if (f.isFile() && f.exists()) {
InputStreamReader sr = new InputStreamReader(new FileInputStream(f), code);
BufferedReader bf = new BufferedReader(sr);
String line;
int i = 0;
String saveOrUpdateFlag = "save";
while ((line = bf.readLine()) != null) {//遍历文件的每一行
String[] lineDataArray = line.split("\\|");//将每行以|分割
String vipidcard = lineDataArray[2];
String cardlevel = lineDataArray[3];//卡等级A=金卡,B=银卡,D=无效卡
String vipname = lineDataArray[8];
String vipType = "2";//急难救助
String idType = "0";//0=身份证
String vipRemark = lineDataArray[8];//补充说明
String isactive = "1";//有效
String oprId = "sys";
String brhId = "00000000000000";//从急难救助同步的VIP
try{
Amsvipinfo amsvipinfo = findInVIPByCard(vipidcard,brhId);
if(amsvipinfo == null){
saveOrUpdateFlag = "save";
saveToAmsVIPInfo(brhId,oprId, vipname, vipidcard, cardlevel, vipType, idType, vipRemark, isactive);
}else{
saveOrUpdateFlag = "update";
updateToAmsVIPInfo(brhId,oprId, vipname, vipidcard, cardlevel, vipType, idType, vipRemark, isactive);
}
}catch(Exception e){
LOG.ADMININFO("急难救助-"+saveOrUpdateFlag+"-文件第"+(i+1)+"行发生错误:"+line.toString());
e.printStackTrace();
}
i++;
}
}
}
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics