4

真正的新手问题:

我有一个需要阅读的 .csv 文件。我把它放在原始文件夹中。为方便起见,我使用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 构造函数中使用 StringReader 而不是 FileReader。

于 2012-12-19T22:27:02.637 回答