java - java中读取文本文件时出现空指针

标签 java android

从文件读取数据时出现空指针异常。如果它返回垃圾值如何处理。如果我不给修剪一些垃圾值(value)。 我的代码是:

BufferedReader br = null;
try {           
    String sCurrentval = "";
    br = new BufferedReader(new FileReader("filepath"));
    while ((sCurrentval = br.readLine()) != null) {
        System.out.println("Reading from File "+sCurrentval);
    }
    if(sCurrentval != null){
        sCurrentval = sCurrentval.trim();
    }
    System.out.println("outside :  Reading from File "+sCurrentval);
    if(sCurrentval != null && !sCurrentval.equalsIgnorecase("")){
        try{
            val = Integer.parseInt(sCurrentval.trim());
        }catch(Exception e){
            e.printStackTrace();
        }
    }else{
        System.out.println("Reading Value  null ");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (br != null)br.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

最佳答案

您的 BufferedReader br = null; 位于 try 中。但是您的finally也使用了相同的变量br

 try
    {
    //
    BufferedReader br = null; // declared with in try
    //
    }
    finally {
    try {
    if (br != null) // In this line the br is not identified 
     br.close();
    } catch (IOException ex) 
    {
    ex.printStackTrace();
    }

尝试在 try 之外声明 BufferReader

BufferedReader br = null;

然后你的 while 循环仅用于打印变量的值。在 while 内包含以下 if else 条件,然后尝试以下代码。

while ((sCurrentval = br.readLine()) != null)
            {
                System.out.println("Reading from File " + sCurrentval);
                if (sCurrentval != null && !sCurrentval.trim().isEmpty())
                {
                    try
                    {
                        val = Integer.parseInt(sCurrentval.trim());
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    System.out.println("Reading Value  null ");
                }
            }

关于java - java中读取文本文件时出现空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18462056/

相关文章:

android - 在布局 xml 中根据 android 中的宽度设置 View 高度

java - 对 AOSP Launcher3 进行编程以隐藏特定应用程序

java - 带参数的 for 循环中的多线程

java - 线程 "AWT-EventQueue-0"java.lang.NoClassDefFoundError 中的异常

java - 数组的排列

java - 基于逻辑构造对象类型——这可以做到吗?

android - Textview drawable 不在远程 View 中显示可绘制图像

android - 加力无方向

java - Eclipse 中的 "import java.beans.XMLEncoder"问题

android - preferenceactivity 中没有带有 app-compat-v21 库的 actionBar?