繁体   English   中英

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

[英]How do I read lines from a file and store them into an array

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

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

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();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM