尝试使用扫描仪读取res / raw中的文本文件

时间:2013-03-01 00:59:59

标签: android nullpointerexception java.util.scanner android-resources

您好,

我正在尝试使用Scanner读取文件,因此我可以使用字符串的输入来构造其他对象。但是,我的扫描仪在尝试创建它时始终会抛出NullPointerException。我在pig.txt文件夹中有一个res/raw文本文件,但我的扫描仪似乎无法访问它。我不知道我做错了什么。我已经注释掉了该方法的其他代码但仍然有例外。

public void loadAchievements() {
    try {
        Scanner s = new Scanner(getResources().openRawResource(R.raw.pig));

        /**
         * s = s.useDelimiter("."); Scanner StringScanner; StringScanner =
         * new Scanner(s.next()); StringScanner =
         * StringScanner.useDelimiter(":"); String keep =
         * StringScanner.next(); String StringKeeper = StringScanner.next();
         * this.achievementBoard.add(new Achievement_Item(keep,
         * StringKeeper)); StringScanner.close(); s.close();
         **/
    } catch (NullPointerException e) {
        e.printStackTrace();
        System.out.println("NULLPOINTER");
    }
}

2 个答案:

答案 0 :(得分:1)

I had this problem today, and I resolved somehow.
I know that old question, but I would share it if others have stuck.





 public class Question {

        private int numberOfQuestion;
        private String[] myquestion;

        public Question(InputStream file_name) {
            Scanner scanner = null;

            try {
                scanner = new Scanner(file_name);

            } catch (Exception e) {
                Log.d("Question", "Scanner :" + e);
                System.exit(1);
            }

            this.numberOfQuestion = scanner.nextInt();
            scanner.nextLine();
            myquestion = new String[numberOfQuestion];

            for (int i = 0; i < numberOfQuestion; ++i) {
                myquestion[i] = scanner.nextLine();

            }

            scanner.close();


        }
    ---------------------------------------------------------
call:

try { 
  MyScanner myScanner = new MyScanner(getResources().openRawResource( R.raw.input_question)); 
   } catch (Exception e) { 
        Log.d("Error", "input_question.txt"); 
  }

答案 1 :(得分:0)

openRawResource()方法可以用于打开可绘制,声音和原始资源;它会在字符串和颜色资源上失败。由于您的pig.txt是一个包含String的文本文件,因此openRawResource()将无法打开新流,因此您的流为空。