0

我需要 ftp 下载并将文件转换为字符串,这样:

    public static boolean leArquivos(String inicioArquivo) {
    try {
        FTPClient mFtp = new FTPClient();
        mFtp.connect(FTPHOST, PORTA);
        mFtp.login(USUARIO, SENHA);
        FTPFile[] ftpFiles = mFtp.listFiles();
        int length = ftpFiles.length;
        for (int i = 0; i < length; i++) {
            String nome = ftpFiles[i].getName();
            String[] itens = nome.split("_");
            boolean isFile = ftpFiles[i].isFile();
            String arquivo_id = itens[0];
            if (isFile && (arquivo_id.equals(inicioArquivo))) {
                // the follow lines work if outside the for loop
                InputStream inStream = mFtp.retrieveFileStream(nome.toString());
                String arquivoLido = convertStreamToString(inStream);
                String[] arquivoLidoPartes = arquivoLido.split("#");
                Retorno.adicionaRegistro(nome, arquivoLidoPartes[0], arquivoLidoPartes[1], false);
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

这将读取 'inicioArquivo_anything.txt' 并放入一个字符串。FTP 和 Registro.adicionaRegistro 工作正常。如果我将 'if' 内的 4 行移到 'for' 循环之外,它适用于单个文件。我需要对几个文件执行操作。

抱歉英语不好(Java 也很差)...

编辑

以这种方式工作

转换代码:

    private static String convertStreamToString(InputStream is, FTPClient mFtp) throws IOException { // added the client
    BufferedReader r = new BufferedReader(new InputStreamReader(is));
    StringBuilder total = new StringBuilder();
    String line;
    while ((line = r.readLine()) != null) {
        total.append(line);
    }
    r.close(); // close stream
    is.close(); // close stream
    mFtp.completePendingCommand(); 
    return total.toString();
}

并改变了这一点:

String arquivoLido = convertStreamToString(inStream, mFtp);
inStream.close();
4

1 回答 1

2

正如 API 文档中所写,您必须关闭流(在转换之后)并调用该completePendingCommand方法来完成并检查传输的状态:

FTPClient.html#retrieveFileStream

而且,在所有程序中,基础知识:不要忘记关闭 Streams !

于 2013-05-17T13:22:52.773 回答