[英]How do I read lines from a file and store them into an array
So basically what I'm trying to do is read this file called Products.csv, and then I want to store each lines of it (445 lines) into an array of length 445. 因此,基本上我想做的是读取名为Products.csv的文件,然后将其每一行(445行)存储到长度为445的数组中。
For some reason, if I typed System.out.println (lines[2]); 由于某种原因,如果我键入System.out.println(lines [2]); for example, it does read out the line 2 of the file, however, if I used a loop to read out all the lines with this code System.out.println (lines[a]) while in a loop, it shows me all null null null....
例如,它确实读出了文件的第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);
}
}
You're reading the lines into one Lab2 object, then creating a totally new different Lab2 object to display the results. 您正在将这些行读取到一个Lab2对象中,然后创建一个全新的不同Lab2对象以显示结果。 Don't do that since the 2nd Lab2 object has not been filled with data and thus its array is filled with nulls.
不要这样做,因为第二Lab2对象尚未填充数据,因此其数组填充了空值。 Instead use the same Lab2 object for both reading and displaying.
而是使用相同的 Lab2对象进行读取和显示。
Change 更改
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);
}
to 至
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.