Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InputStream - Dealing with network changes

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.

like image 291
Tsikon Avatar asked Nov 12 '22 14:11

Tsikon


1 Answers

Your application is stuck. The solution to that is to set a read timeout, as discussed in this question. If the timeout occurs a SocketTimeoutException will be thrown.

like image 68
user207421 Avatar answered Nov 15 '22 04:11

user207421