开发者

Android FileReader from R.raw.file

Really newbie question:

I have a .csv开发者_JAVA百科 file that I need to read. I've put it in the raw folder. For convenience, Im' using the http://opencsv.sourceforge.net/ library for reading the file. The library provides this method for creating a CSVReader object:

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

But I don0't get how to point this constructor to my file, since the file in Android is usually referenced like R.raw.file rather than a String address to the file.

Any help would be greatly appreciated.


You want to do something like this -

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");
       }
   }
}


You can use this solution to get a String from the raw resource: Android read text raw resource file

then use StringReader instead of FileReader with the CSVReader constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜