简体   繁体   English

使用Apache FTPClient 3.1和FTP.BINARY_FILE_TYPE上传后,JAVA 6和损坏的文件

[英]JAVA 6 and corrupted files after uploading using Apache FTPClient 3.1 and FTP.BINARY_FILE_TYPE

I'm really going bonkers on this. 我真的对此疯狂。

I'm writing a small Java (must be SDK 6) tool using the commons-net-3.1.jar library to upload a bunch of files to another bunch of servers simultaneously. 我正在编写一个小型Java(必须是SDK 6)工具,使用commons-net-3.1.jar库将一堆文件同时上传到另一组服务器。 I will use it with .jpg images mostly. 我将主要使用.jpg图像。 I set the connection to BINARY_FILE_TYPE before anyone ask :) 在有人问:)之前我将连接设置为BINARY_FILE_TYPE

When I try and run it, everything goes smooth but sometimes, after uploading the images, they have "small lines" on them, like if the file had been corrupted on its way. 当我尝试运行它时,一切都顺利但有时,在上传图像后,它们上面有“小线条”,就像文件在路上被损坏一样。

This little piece of code is the one who does all the work. 这段代码就是完成所有工作的人。 Any clues about how should I manage the first catches when the os.write fails in order to keep the file uploading right? 有关在os.write失败时如何管理第一次捕获以保持文件正确上传的任何线索?

try {
    InputStream is = new FileInputStream(rutaFichero);
    OutputStream os = ftp.storeFileStream(nombreFichero);
    byte buf[] = new byte[8192];
    bytesRead = is.read(buf);

    while ((bytesRead = is.read(buf)) != -1) {
        try {
            os.write(buf, 0, bytesRead);
        } catch (IOException ioe) {
        } catch (NullPointerException npe) {
        }
    }

    is.close();
    try {
        os.close();
        completado = ftp.completePendingCommand();
        if (completado) {
    } catch (NullPointerException npe) {}
}

Out of curiosity, I thought it could be just bad conditions on the line so I checked the sizes of files after transfering for some days and... none of them matched! 出于好奇,我认为这可能只是条件上的恶劣条件所以我在转移了几天之后检查了文件的大小并且......没有一个匹配! WTF!? WTF!?

You have a bug in the first line here: 你在第一行有一个错误:

bytesRead = is.read(buf);

while ((bytesRead = is.read(buf)) != -1) {
    try {
        os.write(buf, 0, bytesRead);
    } catch (IOException ioe) {
    } catch (NullPointerException npe) {
    }
}

You never write the first buf contents. 你永远不会写第一个buf内容。 You just read them and then read subsequent chunk in while loop. 您只需读取它们,然后在while循环中读取后续块。 Remove the first is.read() and you'll be fine. 删除第一个is.read() ,你会没事的。

It's another reason to avoid such tedious code and go for utility methods such as IOUtils.copy() : 这是避免这种繁琐代码的另一个原因,并采用IOUtils.copy()等实用方法:

InputStream is = new FileInputStream(rutaFichero);
OutputStream os = ftp.storeFileStream(nombreFichero);
IOUtils.copy(is, os);
is.close();
os.close();

当一些人给我发电子邮件给我一个关于确保在登录后将模式类型设置为二进制的建议时,问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM