0

I've the following code:

try{
                fileOutputStream = new FileOutputStream(downloadFile1);
                outputStream1 = new BufferedOutputStream(fileOutputStream);

                boolean success = ftpclient.retrieveFile(completePath.get(i), outputStream1);

                if (success) {
                    System.out.println(completePath.get(1)+" downloaded!");
                }
            }finally {
                if (outputStream1!=null) outputStream1.close();
                if(fileOutputStream!=null) fileOutputStream.close();

            }

IntelliJ is giving error that FileOutputStream needs to be closed too.

whereas if I change the stream closing order in finally block

  finally {  
     if(fileOutputStream!=null) fileOutputStream.close();
     if (outputStream1!=null) outputStream1.close();
                }

then there are no errors but the files are not downloaded completely as the streams was closed ahead.

Can someone suggest the right way to do this?

user207421
  • 305,947
  • 44
  • 307
  • 483
avi
  • 1,847
  • 3
  • 16
  • 17

2 Answers2

2

The docs of the close method of BufferedOutputStream (inherited from FilterOutputStream) says

The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.

So IntelliJ is clearly wrong. If in doubt trust the documentation, not the IDE's warnings - they are warnings and not errors for a reason.

That said, you should use a try-with-resources statement.

And you also do not need an intermediate variable, you can construct the FOS and immediately pass it as argument to the BOS constructor.

the8472
  • 40,999
  • 5
  • 70
  • 122
  • thanks for the information @the8472, I tried try-with-resources which worked perfectly fine. – avi Jun 16 '17 at 20:55
1

You should use try-with-resources:

private static void printFileJava7() throws IOException {

    try(  FileInputStream     input         = new    FileInputStream("file.txt");
          BufferedInputStream bufferedInput = new     BufferedInputStream(input)
    ) {

        int data = bufferedInput.read();
        while(data != -1){
        System.out.print((char) data);
        data = bufferedInput.read();
    }
}

See:

Anderson Marques
  • 808
  • 8
  • 13