java - 如何从文件中读取行并将其存储到数组中

标签 java arrays

所以基本上我想做的是读取这个名为 Products.csv 的文件,然后我想将它的每一行(445 行)存储到长度为 445 的数组中。

出于某种原因,如果我输入 System.out.println (lines[2]);例如,它确实读出了文件的第 2 行,但是,如果我在循环中使用循环使用此代码 System.out.println (lines[a]) 读出所有行,它会显示所有内容空空空....

public class Lab2 
{
        String [] lines = new String [446];
        int x = 0;
    File inFile;

    public long ReadFile(String sfile) throws IOException 
    {
        inFile  = new File(sfile);
        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        String sline = null;
        while ((sline=reader.readLine()) != null) 
        {
                lines[x]=sline;
                x++;
        }
        reader.close();  
        return inFile.length();
         }

        public void OutputLines (String [] s)
        {
            for (int a=0;a<s.length;a++)
            {
               System.out.println (s[a]); 
            }
        }

    public static void main(String[] args)
    {
        try
        {
            Lab2 read = new Lab2();
            read.ReadFile("Products.csv");

        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
        }

                Lab2 reader = new Lab2 ();
                reader.OutputLines(reader.lines);
        }
}

最佳答案

您正在将这些行读入一个 Lab2 对象,然后创建一个全新的不同 Lab2 对象来显示结果。不要这样做,因为第二个 Lab2 对象尚未填充数据,因此其数组填充有空值。而是使用相同 Lab2 对象来读取显示。

改变

public static void main(String[] args)
{
    try
    {
        Lab2 read = new Lab2();
        read.ReadFile("Products.csv");

    }
    catch (IOException e)
    {
        System.out.println(e.getMessage());
    }

            Lab2 reader = new Lab2 ();
            reader.OutputLines(reader.lines);
    }

public static void main(String[] args) {
    try {
        Lab2 read = new Lab2();
        read.ReadFile("Products.csv");

        // *** display data from the same Lab2 object ***
        read.OutputLines(); // this shouldn't take a parameter
    } catch (IOException e) {
        e.printStacktrace();
    }

关于java - 如何从文件中读取行并将其存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26321024/

相关文章:

javascript - GWT:将处理程序添加到 native js 事件 onafterprint

java - 座位定位器 - 3D 数组 (Java)

arrays - 从 Fortran 中的数组中删除索引值之后的所有行

javascript - 如何使用 For 循环反向打印字符串?

java - 导入类时的奇怪行为

java - 从套接字以小端字节顺序读取无符号整数

java - JAX-RPC com.sun.xml.rpc.client.BasicService 未找到

java - 如何通过本地计算机远程连接 Apache 服务器 (http ://149. 4.223.238:8080)

C++比较字符串数组元素

arrays - 如何在 Bash 中复制数组?