您的位置:首页 > 编程语言 > Java开发

JAVA通过ftp远程获取文件并压缩

2016-02-28 13:28 363 查看

①通过ftp远程获取文件

public boolean getftp(String host, String login, String pass,

String remoteFile, String localFile, String filename)
throws Exception {
boolean resultFlg = false;
FtpClient ftp = new FtpClient();
try {
ftp.openServer(host);
try {
ftp.login(login, pass);
ftp.binary();
OutputStream out = new FileOutputStream(localFile);
TelnetInputStream ftpIn = ftp.get(remoteFile);
byte[] buff = new byte[204800];
int len = 0;
try {
while ((len = ftpIn.read(buff)) != -1) {
out.write(buff, 0, len);
resultFlg = true;
}

} catch (IOException ioe) {
resultFlg = false;
} finally {
if (ftpIn != null) {
ftpIn.close();
}
if (out != null) {
out.close();
}
}
} catch (Exception ex) {
resultFlg = false;
} finally {
ftp.closeServer();
}
} catch (Exception e) {
}


return resultFlg;

}

注意:文件名含有【中文名称】可能会乱码,要在shell中设置编码格式unix系统查看编码格式命令(locale)

unix(LANG) SJIS:

ja_JP.PCK; EUC:ja; UTF8:ja_JP.UTF-8

#!/bin/csh

setenv LANG ja_JP.PCK


②文件压缩代码

private void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.exists()) {
if (file.isDirectory()) {
parentPath += file.getName() + File.separator;
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
writeZip(files[i], parentPath, zos);
}
} else {
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));
String zipName = parentPath + file.getName();
ZipEntry ze = new ZipEntry(new String(zipName.getBytes(),"Shift_JIS"));
zos.putNextEntry(ze);
byte[] content = new byte[1024];
int len;
while ((len = fis.read(content)) != -1) {
zos.write(content, 0, len);
zos.flush();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (dis != null) {
dis.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
}
}
}
}
}

注意:如果被压缩的文件含有中文,要用apache的ant.jar的压缩工具

不要用Java自带的压缩工具包import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;因为会乱码。


③删除文件夹及文件夹中文件

private boolean deleteDir(File dir) {
if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
}


到此结束

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