gpt4 book ai didi

java - 来自 R.raw.file 的 Android FileReader

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:53 25 4
gpt4 key购买 nike

真正的新手问题:

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

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

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

如有任何帮助,我们将不胜感激。

最佳答案

你想做这样的事情 -

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

关于java - 来自 R.raw.file 的 Android FileReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7087397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com