簡體   English   中英

如何讀取文本文件並將其行添加到 Java 中的數組中?

[英]How to read a text file and add lines of it into an array in Java?

我是編碼新手,我想知道如何將文本文件的行添加到程序中的數組中。 我的代碼如下所示:

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 我該如何解決?

我不確定我的答案。 我認為這是因為您忘記將 java io package 導入程序。 希望你明白了。

  • BufferedReader object 是 null 並且您正在嘗試訪問這在 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()) - stream API 收集為列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM