2015-09-27 91 views
1

我想要的是一段代碼的和平,它檢查文本文件是否存在。我正在使用java。如何檢查android中是否存在txt文件

我要的是這樣的:

if (the file.txt exists) { do a action } else {do another action } 

的文件是在應用程序的數據文件夾中的文件目錄。謝謝! :P

編輯:我保存這樣的文件:

public class crear_data_mes { 
    String nArchivo_mes = "mes.txt"; 
    Context ctx_mes; 
    FileOutputStream fos_mes; 
    FileInputStream fis_mes; 
    public crear_data_mes(Context ctx) { 
     this.ctx_mes=ctx; 
    } 
    public void escribir_mes(String textoarchivo_mes) { 
     try { 
      fos_mes= ctx_mes.openFileOutput(nArchivo_mes, Context.MODE_PRIVATE); 
      fos_mes.write(textoarchivo_mes.getBytes()); 
      fos_mes.close(); 
     } catch (FileNotFoundException e) { 
      Log.e("Hola", "Hola" + e.getMessage()); 
     } catch (IOException ex) { 
      Log.e("Hola", "Hola"+ex.getMessage()); 
     } 
    } 

    public String leer_mes() { 
     String lectura_mes = ""; 
     try { 

      fis_mes = ctx_mes.openFileInput(nArchivo_mes); 
      int i; 
      int n_mes = 0; 
      char caracter_mes='a'; 
      do { 
       i = fis_mes.read(); 
       if (i!='\n') { 
        caracter_mes = (char)i; 
        lectura_mes=lectura_mes+caracter_mes; 
       } 
      } while (i>0); 
      lectura_mes+="\n"; 
     } catch (Exception e) { } 
     return lectura_mes; 
    } 
} 

回答

2

Fileexitst()方法,已經做了你所需要的。

File file = new File(fileDirectory, "file.txt"); 
if (file.exits()) { 

} 

其中fileDirectory是您存儲文件的目錄。

編輯:

你的情況,你可以使用getFileStreamPath,它返回在哪裏與openFileOutput(字符串,整數)創建的文件存儲在文件系統中的絕對路徑。

E.g.

File file = getFileStreamPath("file.txt"); 
if (file.exits()) { 

} 
+0

文件目錄在哪裏?我的意思是它只是預定目錄 –

+0

你是如何創建文件的? – Blackbelt

+0

用getbytes方法 –

相關問題