从类访问资产文件

时间:2015-02-04 10:32:13

标签: java android android-assets

我在课堂上有这个:private Context mCtx = getBaseContext();

然后下面的代码是我的另一个类,我想从资源文件夹中使用文件dictionary.txt,我得到IO Exception。请帮忙

public class RandomStringGenerator {

    private final char[] generatedLetters = generate4().toCharArray();
        private int formedWordNo = 0;
        private final Set <String> formedWords = wordDictAvail(generatedLetters.toString());


        public Set<String> wordDictAvail (String inword){
            Set<String> set = new HashSet<String>();
            int wa = 0;
                 int dictWordLn;
                 String dictWord;

                 try {
                        is =mCtx.getAssets().open("dictionary.txt");

                     Scanner scanner=new Scanner("is");

                 while (scanner.hasNextLine()) {
                     String currChar;
                int i = 1;
                     dictWord = scanner.nextLine().trim();
            dictWordLn = dictWord.length();
                for (int a = 0; a <= dictWordLn-1 ; a++){
                    currChar = Character.toString(dictWord.charAt(a));
                    if (inword.contains(currChar)){
                        i =i*1;
                                     } else {i=i*2;}
                    }
                if (i==1){
                    set.add(dictWord);
                                     wa++;
                                     }

                                                                    }
                 scanner.close();
                 } catch(IOException e) {
                     e.printStackTrace();
                 }
}

1 个答案:

答案 0 :(得分:0)

在MainActivity中的

或从Activity扩展的任何类声明一个静态上下文

private static Context con; 

分配onCreate()

con = MainActivity.this;

从任何其他活动引用此上下文,如

Context presentContext = MainActivity.con

如果有帮助,请告诉我。