有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

来自R.raw的java Android文件阅读器。文件

真正的新手问题:

我有一本书。我需要读取的csv文件。我把它放在原始文件夹里了。为了方便起见,我正在使用http://opencsv.sourceforge.net/库读取文件。该库提供此方法来创建CSVReader对象:

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

但是我不知道如何将这个构造函数指向我的文件,因为Android中的文件通常像R.raw一样被引用。文件,而不是文件的字符串地址

任何帮助都将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    你想做这样的事-

    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");
           }
       }
    }
    
  2. # 2 楼答案

    您可以使用此解决方案从原始资源获取字符串: Android read text raw resource file

    然后在CSVReader构造函数中使用StringReader而不是FileReader