真的是新手问题:
我有一个我需要阅读的.csv文件.我把它放在原始文件夹中.为方便起见,我’使用http://opencsv.sourceforge.net/库来读取文件.该库提供了此方法来创建CSVReader对象:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
但是我不知道如何将这个构造函数指向我的文件,因为Android中的文件通常被引用为R.raw.file而不是文件的String地址.
任何帮助将不胜感激.
解决方法:
你想做这样的事情 –
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");
}
}
}