4

本当に初心者の質問:

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

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

しかし、Androidのファイルは通常、ファイルへの文字列アドレスではなくR.raw.fileのように参照されるため、このコンストラクターを自分のファイルにポイントする方法がわかりません。

どんな助けでも大歓迎です。

4

2 に答える 2

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");
       }
   }
}
于 2011-08-17T02:54:44.897 に答える
0

このソリューションを使用して、生のリソースから文字列を取得できます: Android read text raw resource file

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

于 2012-12-19T22:27:02.637 に答える