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