Android check if file exists

In this Android tip, I am going to show you how to check if a file on the internet exists. This is useful as you want to check the file existence before you read or download the file. To achieve this goal, you can use HttpURLConnection class. This class allows you open a connection to file url on a remove server. Then from the HttpURLConnection connection object, it is possible to get a response code from the server. Commonly used response codes are 200 (HTTP_OK), 404 (HTTP_NOT_FOUND), 301 (HTTP_MOVED_PERM), 302 (HTTP_MOVED_TEMP) , and 303 (HTTP_SEE_OTHER). The code to check file existence can consume much time. So, you should place the code in a separated thread to avoid unresponsive problem and to provide the user status messages at the time you begin checking the file, checking in progress, and after the checking process finished.
Now to have an example application on checking if file exists, you create a new project naming CheckFileExists. Then, in the activity_main.xml file, you add an EditText, a Button, and a TextView. The EditText allows you to input a file url. The Button is clicked to check the file existence and the TextView displays status messages.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.checkfileexists.MainActivity"
   android:orientation="vertical"
   >
  
   <EditText
     android:id="@+id/txturl"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:hint="Enter file url"
     />
   <Button
     android:id="@+id/btcheck"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Check"
     android:onClick="checkFileExists"
     />
<TextView
     android:id="@+id/txtstatus"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
    
     />
  
</LinearLayout>



Here is the content of the MainActivity class to check if an input file url exists or not.

 package com.example.checkfileexists;
import java.net.HttpURLConnection;
import java.net.URL;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

EditText txturl;
TextView txtstatus;
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     txturl=(EditText)findViewById(R.id.txturl);
     txtstatus=(TextView)findViewById(R.id.txtstatus);
          
   }
  
   public void checkFileExists(View view){
   String urlString=txturl.getText().toString();
   if(!urlString.equals("")){
   CheckFileExistTask task=new CheckFileExistTask();
   task.execute(urlString);
   }
   }
  
   private class CheckFileExistTask extends AsyncTask<String, Void, Boolean>
   {
   @Override
   protected void onPreExecute() {
   txtstatus.setText("Checking the file...");
   }
   @Override
   protected Boolean doInBackground(String... params) {
   try {
   // This connection won't follow redirects returned by the remote server.
   HttpURLConnection.setFollowRedirects(false);
   // Open connection to the remote server
   URL url=new URL(params[0]);
   HttpURLConnection con = (HttpURLConnection) url.openConnection();
   // Set request method
   con.setRequestMethod("HEAD");
   // get returned code
   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
  
   }
   catch (Exception e) {
   e.printStackTrace();

   return false;

   }
   }
   @Override
   protected void onPostExecute(Boolean result) {
   // Update status message
   if (result==true)
   {
   txtstatus.setText("File exists");
   txtstatus.setTextColor(Color.parseColor("#44aa77"));

   }
   else
   {
   txtstatus.setText("File not exist");
   txtstatus.setTextColor(Color.parseColor("#ff1111"));

   }
   }
   }
  
  
  
}


Before running the example application, you need to add a permission to use internet in the AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"/>

Android-check-if-file-exists

Posted by: Dara | post date: 11-09-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.