Search code examples
javaandroidandroid-filefile-exists

How can I know a file exists or not?


I wrote this code on android to learn whether a .txt file exists or not.

    File file_a =new File("a.txt");

 InputStream in3 = getResources().openRawResource(R.raw.b);
         FileOutputStream out3 = null;


        try {   out3=openFileOutput("a.txt",Context.MODE_WORLD_WRITEABLE);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
         byte[] buff3 = new byte[1024];
         int read3 = 0; 

         try {
            while ((read3 = in3.read(buff3)) > 0) {
               out3.write(buff3, 0, read3);
            }
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace(); 
        } finally {
              try {
                in3.close();
                out3.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         }

    boolean a=file_a.exists();

It always returns false.

How can I fix this?


Solution

  • I found solution.I tried the read file if its get the catch block it is not exist. thanks everyone.

    try {
            FileInputStream deneme=openFileInput("a.txt");
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
             kopyala();
            e1.printStackTrace();
        }