2011-08-17 62 views
4

真的很新手問題:來自R.raw.file的Android FileReader

我有一個.csv文件需要閱讀。我把它放在原始文件夾中。爲了方便,Im'使用http://opencsv.sourceforge.net/庫來讀取文件。該庫提供了這種方法用於創建CSVReader對象:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); 

但我don0't得到如何此構造指向我的文件,因爲在Android中的文件通常喜歡R.raw.file引用,而不是該文件的字符串地址。

任何幫助將不勝感激。

回答

6

你想要做這樣的事情 -

public void readCSVFromRawResource(Context context) 
{ 
    //this requires there to be a dictionary.csv file in the raw directory 
    //in this case you can swap in whatever you want 
    InputStream inputStream = getResources().openRawResource(R.raw.dictionary); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 

    try 
    { 
     String word;//word 
     int primaryKey = 0;//primary key 
     Map dictionaryHash = new HashMap(); 

     while ((word = reader.readLine()) != null) 
     { 
      if(word.length() < 7) 
      { 
       dictionaryHash.put(primaryKey,word); 
       primaryKey++; 



       if(primaryKey % 1000 == 0) 
        Log.v("Percent load completed ", " " + primaryKey); 
      } 
     } 

     //write the dictionary to a file 
     File file = new File(DICTIONARY_FILE_NAME); 
     BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(DICTIONARY_FILE_NAME)); 
     ObjectOutputStream oos = new ObjectOutputStream(fos); 
     oos.writeObject(dictionaryHash); 
     oos.flush(); 
     oos.close(); 
       Log.v("alldone","done"); 

    } 
    catch (Exception ex) { 
     // handle exception 
     Log.v(ex.getMessage(), "message"); 
    } 
    finally 
    { 
     try 
     { 
      inputStream.close(); 

     } 
     catch (IOException e) { 
      // handle exception 
      Log.v(e.getMessage(), "message"); 
     } 
    } 
} 
+0

乾杯隊友,太棒了! – fred