0

你好,

我正在尝试使用 a 读取文件,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");
    }
}
4

2 回答 2

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"); 
  }
于 2014-11-16T19:22:50.553 回答
0

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

于 2013-03-01T01:30:47.473 回答