设为首页 收藏本站
查看: 1358|回复: 0

[经验分享] java从FTP获取文件,解压缩,读取文件,拷贝文件,删除文件等一系列功能

[复制链接]

尚未签到

发表于 2016-6-11 06:27:20 | 显示全部楼层 |阅读模式
//往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++;
}
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228787-1-1.html 上篇帖子: FTP客户端软件FileZilla使用教程(转自:http://hi.baidu.com/%B8%DF%C7%E5%D6%AE%D3%D1/blog/item/ 下篇帖子: 使用sun.net.ftp.FtpClient进行上传功能开发,在jdk1.7上不适用问题的解决
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表