Вопрос

InputStreamReader throws an NPE as follows when I execute this code on the second iteration of the for loop. The code works perfectly for the first iteration and returns the following NPE on the second iteration. I am using the code snippet to read contents of specific file from an FTP location and display them. Please note all the lines till the new InputStreamReader work perfectly even on second iteration. Any ideas why?

Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
at com.test.txtweb.server.task.CallBackRetryTask.main(CallBackRetryTask.java:229)

Here is the source code:

public static void main(String[] args){
    String strDate = "20130805";

    FTPClient ftpClient = new FTPClient();

    try {
        ftpClient.connect(host);
        String pathToFiles = "/path/to/File";
        String ftpFileName = "";
        List<String> ftpFileNames = null;
        InputStream iStream;
        if(ftpClient.login(username, password)){
            ftpClient.enterLocalPassiveMode(); 
            FTPFile[] ftpFiles = ftpClient.listFiles();
            ftpFileNames = new ArrayList<String>();
            for (FTPFile ftpFile : ftpFiles) {
                ftpFileName = ftpFile.getName();
                if(ftpFileName.contains(strDate)){
                    iStream = ftpClient.retrieveFileStream(pathToFiles + ftpFileName);
                    System.out.println(ftpClient.getReplyString());

                    InputStreamReader isr = new InputStreamReader(iStream); //Error on this line on second iteration
                    BufferedReader br = new BufferedReader(isr);

                    String line = ""; 

                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }

                }
            }
        }
Это было полезно?

Решение

Figured out the issue after quite a lot of debugging. I was not calling the completePendingCommand() after transferring the file to check the status of the transfer.

The API for FTPClient.retrieveFileStream() states that to finalize the file transfer you must call FTPClient.completePendingCommand() and check its return value to verify success. After correcting this issue, everything started working fine.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top