2012-01-27 93 views
0

我是一個android新手,並寫這個代碼的文件處理,但由於某種原因,我總是從文件中取回空值。我也嘗試使用readline(),但得到了相同的結果。將不勝感激任何幫助。文件閱讀不適用於android

 @Override 
     public void onClick(View v) 
     { 
      // TODO Auto-generated method stub 
      String file = "test123"; 
      try 
      { 
       OutputStream out = v.getContext().openFileOutput(file, MODE_PRIVATE); 
       InputStream in = v.getContext().openFileInput(file); 
       WriteFile(out); 
       String str = ReadFile(in); 

       Toast.makeText(v.getContext(), str, Toast.LENGTH_LONG); 
      } catch (FileNotFoundException e) 
      { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

public static void WriteFile(OutputStream out) 
{ 
    OutputStreamWriter tmp = new OutputStreamWriter(out); 

    try 
    { 
     for (int i = 0 ; i < 10; i++) 
     { 
      tmp.write(i); 
     } 
    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace();    
    } 
} 

public static String ReadFile(InputStream in) 
{ 
    InputStreamReader tmp = null; 
    String str = "";   

    tmp = new InputStreamReader(in); 
    BufferedReader reader=new BufferedReader(tmp);      

    try 
    { 
     for (int i = 0; i < 10; i++) 
     { 
      str += " " + reader.readLine();    
     }   

    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return str; 
}  

}

+0

我猜錯誤是你使用相同的文件讀取和寫入。嘗試使用不同的文件。 – Yury 2012-01-27 10:38:50

+0

我想從我已經寫入的文件中讀取。 – user1173171 2012-01-27 20:54:20

回答

1

String file = "test123"; 所以,你的文件的路徑應該是{root}/test123 嘗試定義路徑中,您可以訪問,看它是否有書面的東西。 (通常是:到/ mnt /存儲/ your_file) 然後,你就可以決定是否讀/寫過程的工作或不

注:看看FileOutputStream,它已經實現了很多有用的方法

+0

那麼是不是推薦使用openFileOutput()?我有點困惑,因爲openFileOutput(filename)不喜歡輸入中的路徑分隔符。 – user1173171 2012-01-27 20:54:45

+0

使「出」一個對象FileOutputStream工作:) – user1173171 2012-01-28 05:47:01