我正在尝试使用inputstream从我的R.raw文件夹中打开文件。但我总是遇到这个错误:
'The method getResources() is undefined for the type Wordchecker'
当我尝试使用快速修复时,会出现另一个错误。就像这一个:
'The method openRawResource(int) is undefined for the type Object'...
这是我的代码:
public class Wordchecker {
public static void main(String arg[]){
HashSet <String> newset = new HashSet <String>();
try{
//opening file of words
InputStream is = getResources().openRawResource(R.raw.wordlist);
DataInputStream in = new DataInputStream(is);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//reading file of words
while ((strLine = br.readLine()) != null) {
newset.add(strLine); //adding word to the hash set newset
}
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
private static Object getResources() {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:0)
这里的问题是你没有扩展Activity。您无法拨打getResources()
,因为它不存在
如果没有Activity类,则在将上下文作为参数传递之前不能使用getResources()
答案 1 :(得分:0)
您需要在某个地方引用Context,因为getResources()是上下文中的方法。
在构造函数中获取它的实例:
public class Wordchecker {
Context mContext;
public Wordchecker(Context c) {
mContext = c;
init()
}
public void init() {
HashSet <String> newset = new HashSet <String>();
try{
//opening file of words
InputStream is = getResources().openRawResource(R.raw.wordlist);
DataInputStream in = new DataInputStream(is);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//reading file of words
while ((strLine = br.readLine()) != null) {
newset.add(strLine); //adding word to the hash set newset
}
in.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
然后使用以下命令从Activity或Service或任何扩展Context的任何内容创建此类的对象:
Wordchecker wordchecker = new Wordchecker(this);
确保wordchecker = new Wordchecker(this);
位于onCreate()
或