InputStream – Dealing with network changes-Collection of common programming errors

I’m downloading an attachment using Java mail API and whenever there is a small change in network state, my app gets stuck and I have to restart it, it’s not even crashing. This is the code snippet:

InputStream is = bodyPart.getInputStream();

String fileName = MimeUtility.decodeText(bodyPart.getFileName());

// Downloading the file
File f = new File(Constants.getPath() + fileName);
try {
    FileOutputStream fos;
    fos = new FileOutputStream(f);

    byte[] buf = new byte[8*1024];
    int bytesRead;

    while ((bytesRead = is.read(buf)) != -1) {
    fos.write(buf, 0, bytesRead);
    }
    fos.close();
}

What is the best way to deal with this issue? Thanks.