我编写了这个类(来自示例)来下载远程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它给出了错误。但是如果在同一次迭代中我重新初始化连接它的工作原理。 有人有建议吗?
答案 0 :(得分:0)
由于网络流量或文件大小恰好是第146位,您的连接可能会超时。 您可以打印第146个文件名并检查其大小。您还可以增加FTP连接超时时间
ftpClient.setControlKeepAliveTimeout(300); // set timeout to 5 minutes