简体   繁体   English

使用扫描仪读取文件时获取空指针感知

[英]Getting a null pointer exeception when using scanner to read file

I want to read a text file and parse the string until eof..here is a code snippet.. programs.txt is under assets directory 我想读取一个文本文件并解析该字符串,直到eof ..这是一个代码段。.programs.txt位于Assets目录下

    public void insert_programs() throws FileNotFoundException {
    BufferedReader bfr = null;
    try {
        bfr = new BufferedReader(new 
                InputStreamReader(getAssets().open("programs.txt"))); // <-- NPE occurs on that line 

    } catch (IOException e) {
        e.printStackTrace();
    }
    Scanner pgm = new Scanner(bfr);
    pgm.useDelimiter("*{3}");
    while (pgm.hasNext()) {
        String str = pgm.next();
            process(str);
        }
    }

Logs 日志

03-14 18:05:34.936: E/AndroidRuntime(467):  at dalvik.system.NativeStart.main(Native Method)
03-14 18:05:34.936: E/AndroidRuntime(467): Caused by: java.lang.NullPointerException
03-14 18:05:34.936: E/AndroidRuntime(467):  at android.content.ContextWrapper.getAssets(ContextWrapper.java:74)
03-14 18:05:34.936: E/AndroidRuntime(467):  at c.theworld.com.nikhil.Database.insert_programs(Database.java:40)

add this into your code: 将此添加到您的代码中:

bfr = new BufferedReader(new 
            InputStreamReader(this.getAssets().open("programs.txt")));

looks like your BufferedReader is going to null. 看起来您的BufferedReader将为空。 have you tried putting the scanner code inside try catch block. 您是否尝试将扫描仪代码放入try catch块中? if your program gets IOException then bfr will be null and you'll get NPE. 如果您的程序获得IOException,则bfr将为null,您将获得NPE。

public void insert_programs() throws FileNotFoundException { 
    BufferedReader bfr = null; 
    try { 
        bfr = new BufferedReader(new  
                InputStreamReader(getAssets().open("programs.txt"))); 

Scanner pgm = new Scanner(bfr); 
    pgm.useDelimiter("*{3}"); 
    while (pgm.hasNext()) { 
        String str = pgm.next(); 
            process(str); 
        }
    } catch (IOException e) { 
        e.printStackTrace(); 
    } 

    } 

The method ContextWrapper.getAssets() is throwing the NullPointerException . 方法ContextWrapper.getAssets()抛出NullPointerException You are extending ContextWrapper (or another class that extends it) and it looks like that has not been initialized properly. 您正在扩展ContextWrapper (或扩展它的另一个类),并且看起来好像未正确初始化。 The base Context within the ContextWrapper is null. ContextWrapper的基本Context为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM