1

我必须上传一个 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
4

1 回答 1

3

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

我记得默认传输模式是 ASCII,所以非 ASCII 文件可能会损坏。

于 2013-07-09T14:09:41.857 回答