Java 如何从文件中读取行并将它们存储到数组中
所以基本上我要做的是读取这个名为Products.csv的文件,然后我想将它的每一行(445行)存储到一个长度为445的数组中 出于某种原因,如果我键入System.out.println(第[2]行);例如,它确实读取了文件的第2行,但是,如果我在循环中使用一个循环来读取这个代码System.out.println(lines[a])的所有行,它会显示所有nullJava 如何从文件中读取行并将它们存储到数组中,java,arrays,Java,Arrays,所以基本上我要做的是读取这个名为Products.csv的文件,然后我想将它的每一行(445行)存储到一个长度为445的数组中 出于某种原因,如果我键入System.out.println(第[2]行);例如,它确实读取了文件的第2行,但是,如果我在循环中使用一个循环来读取这个代码System.out.println(lines[a])的所有行,它会显示所有null public class Lab2 { String [] lines = new String [446];
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
{
字符串[]行=新字符串[446];
int x=0;
文件填充;
公共长读取文件(字符串sfile)引发IOException
{
infle=新文件(sfile);
BufferedReader reader=新BufferedReader(新文件读取器(infle));
字符串sline=null;
而((sline=reader.readLine())!=null)
{
直线[x]=sline;
x++;
}
reader.close();
返回infle.length();
}
公共无效输出行(字符串[]s)
{
对于(int a=0;a您正在将行读取到一个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();
}