2011-08-17 6 views
4

本当に初心者質問:R.raw.fileのAndroid FileReader

私は読む必要がある.csvファイルがあります。私は生のフォルダに入れました。便宜上、ファイルを読むためにhttp://opencsv.sourceforge.net/ライブラリを使用しています。ライブラリはCSVReaderオブジェクトを作成するために、このメソッドを提供します。

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

しかし、私は、Androidでファイルが通常よりもむしろR.raw.fileのように参照されているので、私のファイルには、このコンストラクタを指すようにどのように取得don0'tファイルへの文字列アドレス。

ご協力いただければ幸いです。

答えて

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

0

あなたは、生のリソースから文字列を取得するには、このソリューションを使用することができます。 Android read text raw resource file

その後、CSVReaderコンストラクタで代わりにFileReaderをのにStringReaderを使用します。

関連する問題