ZipOutputStream + FTPClient出错

时间:2013-06-28 07:50:17

标签: java apache ftp

我要将一个zip文件上传到ftp服务器,这里的zip文件也是动态构建的。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;

public class CommonsNet {
    public static void main(String[] args) throws Exception {
        FTPClient client = new FTPClient();
        FileInputStream fis = null;
        try {
            client.connect("127.0.0.1");
            client.login("phani", "phani");
            String filename = "D://junk.pdf";
            fis = new FileInputStream(new File(filename));
            byte[] bs = IOUtils.toByteArray(fis);
            fis.close();
            OutputStream outputStream = client.storeFileStream("remote.zip");

            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

            zipOutputStream.setLevel(ZipOutputStream.STORED);
            addOneFileToZipArchive(zipOutputStream,
                    "junk.pdf", bs);
            zipOutputStream.close();

            outputStream.close();

            client.logout();
            System.out.println("Transfer done");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void addOneFileToZipArchive(ZipOutputStream zipStream,
            String fileName, byte[] content) throws Exception {
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
        zipStream.putNextEntry(zipEntry);
        zipStream.write(content);
        zipStream.flush();
        zipStream.closeEntry();
    }
}

执行此代码后,文件已成功创建,但我无法打开存档内的文件。 喜欢:

!   D:\phani\remote.zip: The archive is corrupt
!   D:\phani\remote.zip: Checksum error in C:\Users\BHAVIR~1.KUM\AppData\Local\Temp\Rar$DIa0.489\MCReport.pdf. The file is corrupt

1 个答案:

答案 0 :(得分:1)

尝试在登录后添加client.setFileType(FTP.BINARY_FILE_TYPE);

我记得默认传输模式是ASCII,因此非ascii文件可能会导致损坏。

相关问题