1

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;
    }
}
4

2 に答える 2

0

ここでの問題は、アクティビティを拡張しないことです。存在しないため呼び出すことができませgetResources()

Activity クラスがないと、コンテキストをパラメーターとして渡すまで getResources() を使用できません

于 2013-02-16T09:21:23.953 に答える
0

getResources()は Context のメソッドであるため、どこかにContextへの参照が必要です。

コンストラクターでそのインスタンスを取得します。

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

次に、次を使用して、アクティビティまたはサービス、または Context を拡張するものから、このクラスのオブジェクトを作成します。

Wordchecker wordchecker = new Wordchecker(this);

wordchecker = new Wordchecker(this);onCreate()前後にあることを確認してください

于 2013-02-16T09:24:43.463 に答える