【问题标题】:Error in ZipOutputStream + FTPClientZipOutputStream + FTPClient 中的错误
【发布时间】:2013-06-28 07:50:16
【问题描述】:

我要上传一个 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

【问题讨论】:

  • 我尝试了另一种方式,首先我在本地服务器中创建了一个 zip 文件(工作正常),然后我使用以下代码保存在网络服务器中 fis=new FileInputStream("D://local.zip "); client.storeFile("dump.zip", fis);我仍然无法打开存档中的文件

标签: java apache ftp


【解决方案1】:

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

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

【讨论】:

  • 谢谢,它的工作,早些时候我使用 FTPClient.BINARY_FILE_TYPE 作为文件类型。为什么 FTPClient.BINARY_FILE_TYPE 不能正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2010-10-05
  • 1970-01-01
相关资源
最近更新 更多