Solaris上的文件存储目录:
# pwd/export/home/gxq# lsps.txt test test.txt test1.txt test2.txt
通过代码直接将ps.txt和text.txt文件下载为一个压缩文件:
演示代码如下(代码只是为了演示实现方式,逻辑不严密,只供本人学习用):
import java.util.zip.*; import java.io.*; import sun.net.TelnetInputStream; import sun.net.ftp.*; public class CompressFile { /** * @param args */ public static void main(String[] args) throws FileNotFoundException, IOException { // TODO 从FTP服务器下载文件为压缩包 File f=new File("MyZIPFile.zip"); //文件MyZIPFile.zip是最终的压缩包 String fileToDownload = ""; //将要下载的文件名称 TelnetInputStream is = null; byte[] b = new byte[100]; int length = 0; FtpClient ftp = new FtpClient("192.168.1.10",21); ftp.login("root", "root"); if (!ftp.serverIsOpen()){ System.out.println("Failed to login to 192.168.1.10"); return; } ftp.cd("/export/home/gxq");//设置服务器端的工作目录 ftp.binary();//切换传输方式为二进制 if(!f.exists()) //确认压缩文件被创建 { f.createNewFile(); } //用文件输出流构建ZIP压缩输出流 ZipOutputStream zipos=new ZipOutputStream(new FileOutputStream(f)); zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法 fileToDownload = "ps.txt"; is = ftp.get(fileToDownload); zipos.putNextEntry(new ZipEntry(fileToDownload)); //生成一个ZIP entry,写入文件输出流中,并将输出流定位于entry起始处。 DataOutputStream os=new DataOutputStream(zipos); while((length = is.read(b))!= -1) { os.write(b, 0, length); } is.close(); fileToDownload = "test.txt"; is = ftp.get(fileToDownload); zipos.putNextEntry(new ZipEntry(fileToDownload)); //生成一个ZIP entry,写入文件输出流中,并将输出流定位于entry起始处。 os=new DataOutputStream(zipos); while((length = is.read(b))!= -1) { os.write(b, 0, length); } is.close(); os.close();//关闭数据流 } }