【问题标题】:Reading from a file to a list从文件读取到列表
【发布时间】:2013-06-17 18:48:47
【问题描述】:

我正在尝试从文件创建一个列表,然后在我的主类中使用该列表。

这是我的错误:

Exception in thread "main" java.lang.NullPointerException
at Read.ReadFile(Read.java:18)
at Main.main(Main.java:6)

这是我的代码:

import java.util.*;

public class Main {
    public static void main(String args[]){

        List<Integer> a = (new Read()).ReadFile();

        Read z = new Read();
        z.OpenFile();
        z.ReadFile();
        z.CloseFile();
        System.out.println(a);

    }
}

还有其他类:

import java.util.*;
import java.io.*;

public class Read {
    private Scanner x;

    public void OpenFile(){
        try{
            x = new Scanner(new File("numbers.txt"));
        }
        catch(Exception e){
            System.out.println("ERROR");
        }
    }

    public List<Integer> ReadFile(){
        List<Integer> a = new ArrayList<Integer>();
        while(x.hasNextInt()){
            a.add(x.nextInt());
        }
        return a;
    }

    public void CloseFile(){
        x.close();
    }
}

这是我的文本文件:

1 2 3 4 5 6 7 8 9

我希望有人可以帮助我。 附言。我正在自学编程,英语不是我的第一语言,所以如果有初学者的错误,我很抱歉。

【问题讨论】:

  • 您应该在读取构造函数中初始化扫描仪。这样您就无法使用空扫描仪创建读取实例...

标签: java file list


【解决方案1】:
List<Integer> a = (new Read()).ReadFile();

在打开文件之前,您在此处调用ReadFile();。因此,x 将为 null 并导致 NullPointerException

解决此问题的一种方法是:

ArrayList&lt;&gt; 移动到Read 类中并添加get 方法。

【讨论】:

    【解决方案2】:

    你的语句顺序应该是这样的:

        Read z = new Read();// instantiate the reader
        z.OpenFile(); //open the file
        List<Integer> a = z.ReadFile(); //read and hold the values in array
        z.CloseFile(); //close the file
        System.out.println(a); //print the values
    

    不需要第一个语句。获取阅读器,打开文件,读取值,关闭文件,然后打印值。

    【讨论】:

      【解决方案3】:

      在以下行中,您创建了一个新的 Read 实例并立即调用 ReadFile(),而不是首先使用 OpenFile() 创建 Scanner 对象:

          List<Integer> a = (new Read()).ReadFile();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-11
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        相关资源
        最近更新 更多