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();
}
到此结束
阅读更多相关文章推荐
- java 两个通过java代码操作FTP的类,上传下载删除,获取文件
- java通过FTP获取不到文件
- java 两个通过java代码操作FTP的类,上传下载删除,获取文件
- centos6.4下定时通过ftp获取数据库服务器上的文件并且删除远程目录里面的文件
- 通过java代码来下载FTP地址中带中文的文件
- Java通过commons-net.jar包上传ftp文件(样例)
- Java+通过XPath获取XML文件中符合特定条件的节点
- java下载远程http地址的图片文件到本地-自动处理图片是否经过服务器gzip压缩的问题
- ASP.NET获取远程网页下载到本地文件,通过URL生成静态文件的做法
- 有关java对压缩文件的加密(通过密码解密)
- java通过ftp上传、下载文件,遍历文件目录
- 通过jcifs.jar 创建远程文件和文件夹。。。非ftp方式。
- Java语言实现简单FTP软件------>远程文件管理模块的实现(十)
- 利用JAVA获取远程文件及使用断点续传,供学习者使用
- java开发中如何获取远程文件的大小
- java通过apache ftp实现ftp上传文件,下载文件
- Java 通过使用File类获取文件信息
- Java 通过 JNA (Java Native Access) 获取、设置 Windows 操作系统的文件创建时间、文件修改时间、文件访问时间
- 手机通过wifi获取电脑共享的文件----诺基亚远程驱动器篇
- java中通过文件路径获取文件名