我需要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();
答案 0 :(得分:2)
如API文档中所述,您必须关闭流(转换后)并调用completePendingCommand
方法来完成并检查传输的状态:
FTPClient.html#retrieveFileStream
并且,在所有程序中,基础知识:不要忘记关闭Streams !!