java - 文件转换在 for 循环内不起作用

标签 java android

我需要 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();

最佳答案

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

FTPClient.html#retrieveFileStream

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

关于java - 文件转换在 for 循环内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610060/

相关文章:

java - 如何点击div中的文字

java - Jquery 错误 - 调用 Struts 2 操作时

Android:获取作为可移植wifi热点的手机的SSID和密码

Android:If/Else 语句使应用程序崩溃

android - 如何使用协调器布局和自定义工具栏更改 android 标题颜色

java - 发言失败:not bound to tts engine

java - 如何将 DatePicker 设置为当前日期后一个月?

java - Mockito 基于字符串参数的模拟响应

android - Android ImageView 上的减法滤镜(从图像或 View 对象中切出羽毛状椭圆)

java - Android Studio 无法识别导入语句