2012-12-24 91 views
0

嗨,大家好我試圖從Android中的文件中讀取日期。我正在使用Eclipse,程序正在編譯和運行,只是它不打印txt文件的上下文。這裏是我的加載方法閱讀簡單的文本文件

private String load(String filename) { 
     try { 
//   Log.v("Home", " in the load method"); 
      Log.d("Home", " in the load method"); 

      final FileInputStream fis = openFileInput(filename); 
//   final InputStream fis = getResources().openRawResource(R.raw.pages); 

      final BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 
      reader.close(); 
      fis.close(); 
      return sb.toString(); 
     } catch (Exception ex) { 
      return "No entry exists for this file"; 
     } 
    } 

,並在OnCreate我剛剛訪問它

String fileName = "pages.txt"; 
load(fileName); 

pages.txt是在res/raw目錄。我試圖用

final FileInputStream fis = openFileInput(filename); 
// final InputStream fis = getResources().openRawResource(R.raw.pages); 

讀取文件但它沒有打印上下文。

我在onCreate方法

Log.d("File", load(fileName)); 

添加,但在返回catch語句No entry exists for this file.

感謝

+8

您目前正在忽略load方法的返回值。你期望如何工作? –

+0

資源必須通過'getResources()'處理,包中任何地方都沒有名爲'「pages.txt」的文件。堅持'openRawResource' ... –

+0

它的工作現在感謝 –

回答

0

嘗試使用如下,

System.out.println(load(raw.pages)); 



private String load(int id) { 
     try {   
      Resources res = getResources(); 
      InputStream fis = res.openRawResource(id); 
      final BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line); 
      } 
      reader.close(); 
      fis.close(); 
      return sb.toString(); 
     } catch (Exception ex) { 
      return "No entry exists for this file"; 
     } 
    }