所以基本上我想做的是读取这个名为 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/