我需要 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/