FileNotFoundException is being thrown sometimes and i don't know why

174 Views Asked by At

I am trying to run a webservice that return XML format but it sometimes throws FileNotFoundException on 3G network and sometimes works successfully on WIFI network

here is the code of the connection :

      @Override
    protected ArrayList<NewsItemVO> doInBackground(Void... args) {


        try {
            URLConnection conn = new URL(feedUrl).openConnection();
            conn.setConnectTimeout(20000);
            conn.setReadTimeout(20000);
            InputStream in = new BufferedInputStream(conn.getInputStream());
          }
}

and this is the line that throws the exception

 InputStream in = new BufferedInputStream(conn.getInputStream());
2

There are 2 best solutions below

2
On

Before using input stream you could check if it is available or not?

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

0
On

As per documentation :

Signals that an attempt to open the file denoted by a specified pathname has failed.

This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

Since your code is working for most of the times and not working for some times, I suspect that you are getting ConnectionTimeOut.

To dig the issue further, please follow below steps.

1) Declare a long variable t1 and initialize it to System.currentTimeMillis() before try block. declare one more long varaible t2 and get current time after finally block. Check the difference. If the difference is more than connection timeout setting, we can conclude that you are getting connection time outs.

2) Print complete exception stack trace in catch clause.

3) When you get this exception, check the permissions on file and confirm that file is accessible with read/execute permissions.

And one more thing - Since it is working fine in wifi and not working in 3G, I suspect connection timeout is the root cause.