我编写了这个类(来自示例)来下载远程 FTP 文件夹中包含的所有文件的标题。它运行良好,但是当它接近下载文件 #146 时,它会因 NullPointException 而停止。文件#146 存在,实际上我可以将其作为单个文件下载。
在remotePathLong 方法中,所有远程文件夹都写在一行中,并用空格字符隔开。
public void downloadHeader(String remotePathLong, String destPath, int bytes) {
String remotePath;
FTPFile[] fileList;
String[] fileNameList;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
int indice = 0;
int iP = 1;
File downloadFile;
String destFile;
String remoteFile;
byte[] bytesArray;
int bytesRead = -1;
while ((remotePath = getPath(remotePathLong, iP)) != null) {
System.out.println("Loading file list from the server.....");
fileNameList = ftpClient.listNames(remotePath);
for (String file : fileNameList) {
indice += 1;
System.out.println(indice + " - Downloading: " + file);
//Select files
destFile = destPath.concat(file);
downloadFile = new File(destFile);
outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
//Download remote file (from ftp)
remoteFile = remotePath.concat(file);
inputStream = ftpClient.retrieveFileStream(remoteFile);
bytesArray = new byte[bytes];
bytesRead = inputStream.read(bytesArray);
outputStream.write(bytesArray);
//Save into file
outputStream.close();
inputStream.close();
iP += 1;
}
}
} catch (IOException ex) {
} final{
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
catch (IOException ex1) {
System.out.println("Error: " + ex1.getMessage());
}
}
当它到达 bytesRead = inputStream.read(bytesArray) 时,在迭代 #146 时它会给出错误。但是,如果在同一迭代中我重新初始化它的工作连接。请问有人有什么建议吗?