Search code examples
javainputstreamoutputstream

When (how often) to open/close input/output streams?


I am trying to write an FTP client program and I have input and output streams to transfer files between server and my computer.

When I was thinking about how to design the class, I couldn't decide on whether to open up a new InputStream every time I call the function and then immediately close it (as in the example below).

Or just do this in the constructor and close it while quitting the program. Does it matter? Does it make sense to do it this way, especially if the user has the option to decide to upload another file to the server immediately after doing it once?

public class FTPClientP extends FTP{
    private InputStream is;

    public FTPC(String serverAdd, int connection_port){
        is = null;

    }
    public int connectToServer() throws  IOException{

    }

    public boolean uploadToServer(File file) throws IOException{

        boolean uploaded = false;

        is = new FileInputStream(file);

        String fileName = myFile.getName();

        uploaded = ftp.storeFile(fileName, is);

        is.close();

        return uploaded;
    }

}

Solution

  • You should open and close InputStreams,OutputStreams, and other resources like that, as soon as possible (in the nearest scope possible). For example, if i want to send a file the steps are

    1. Open an OutputStream.
    2. Send bytes.
    3. Close OutputStream.

    If you will not close such resources , you will be facing a memory leak.

    You can use try-with resources so you will not accidentally forget to close your resource. You can use any resource you like with try-with resources, as long as it implements the AutoClosable interface. (InputStream and OutputStream indeed implement the AutoClosable interface).

    an example of using try-with resources:

    try (InputStream fis = new FileInputStream(source);
            OutputStream fos = new FileOutputStream(target)){
    
            byte[] buf = new byte[8192];
    
            int i;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    

    Note: both the InputStream AND the OutputStream, are in the try-with resources statement, in the example above.