【问题标题】:How to read a text file and add lines of it into an array in Java?如何读取文本文件并将其行添加到 Java 中的数组中?
【发布时间】:2022-01-07 10:11:43
【问题描述】:

我是编码新手,我想知道如何将文本文件的行添加到程序中的数组中。我的代码如下所示:

import java.io.*;
public class Test {
    
    static String [] name = new String [3];
    static String [] surname = new String [3];
    
    public static void main(String[] args) {
        try{
            BufferedReader reader =null;
            String currentLine = reader.readLine();
            reader=new BufferedReader(new FileReader("Names.txt"));

            int x=0;
            
            while(currentLine!=null){
                name[x]=reader.readLine();
                currentLine=reader.readLine();
                surname[x]=reader.readLine();
                currentLine=reader.readLine();
                x=x+1;
            }
        }
        catch(Exception e){
            System.out.println("The following error occured:" + e.getMessage());
        }
        
        for(int x =0; x<name.length; x++){
            System.out.println(
            "name:" + name[x] + "\n"+
            "surname: " + surname[x] +"\n"
            );
        }
    }

我得到的错误是Cannot invoke "java.io.BufferedReader.readLine()" because "reader" is null。我该如何解决?

【问题讨论】:

  • 您的 currentLine 为空,因此,它永远不会进入语句不为空的 while 循环。

标签: java arrays file io populate


【解决方案1】:
  • BufferedReader 对象为空,您正在尝试访问,这在 java 中是不可能的。
  • 我不明白你到底想做什么,但你可以做这样的事情。
public class Task3 {

    static String [] name = new String [3];
    static String [] surname = new String [3];
    
    public static void main(String[] args) {
        try{
            BufferedReader reader =null;
            reader=new BufferedReader(new FileReader("/home/ancubate/names.txt"));
            List<String> lines = reader.lines().collect(Collectors.toList());
            int x=0;
            
            while(lines.size() != (x+1)){
                name[x]=lines.get(x);
                surname[x]=lines.get(x);
                x=x+1;
                
            }
        }
        catch(Exception e){
            System.out.println("The following error occured:" + e.getMessage());
        }
        
        for(int x =0; x<name.length; x++){
            System.out.println(
            "name:" + name[x] + "\n"+
            "surname: " + surname[x] +"\n"
            );
        }
    }

}

  • reader.lines() - 从文件中获取所有行
  • collect(Collectors.toList()) - 流 API 收集为列表

【讨论】:

    【解决方案2】:

    我不确定我的答案。我认为是因为您忘记将 java io 包导入程序。希望你明白了。

    【讨论】:

    • 我确实添加了它,但不幸的是它仍然给出了同样的错误。
    • 如果不确定,请优先评论而不是回答
    猜你喜欢
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    相关资源
    最近更新 更多