Java - 从csv文件中读取空值
问题描述:
当我从老师那里读取数据时,我得到一个空值。 csv文件。属于att [0]的列1工作,但att [1]返回3个空值。Java - 从csv文件中读取空值
我的CSV看起来是这样的: 1,墨菲 2,戴维斯先生 3,女士辛普森 每个在单独的行,即行1 - > 1,墨菲等
这里是我的代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV
{
public static void main(String[] args)
{
//Input file which needs to be parsed
String readTeachers = "teacher.csv";
BufferedReader fileReader = null;
//Delimiter used in CSV file
final String DELIMITER = ",";
try
{
String line = "";
//String line = inFile.readLine();
//Create the file reader
fileReader = new BufferedReader(new FileReader(readTeachers));
int count=0;
String[] att = new String[10];
//Read the file line by line
while ((line = fileReader.readLine()) != null)
{
//Get all tokens available in line
String[] tokens = line.split(DELIMITER);
int i=0;
count++;
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break;
}
}
//System.out.println(count);
//System.out.println(att[1]);
}
catch (Exception e) {
e.printStackTrace();
}
finally
{
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答
您的问题在于,您在for循环中有一个break语句,它在第一次迭代结束时退出循环。因此,您只需在数组的第一个索引中添加一个值。拿出这个声明,它应该没问题。
for(String token : tokens)
{
att[i] = token;
i++;
//Print all tokens
// System.out.println(token);
System.out.println(att[1]);
break; // <---- ***take this out***
}
即使在第一次迭代中,当您只为att [0]赋值时,您正在打印'att [1]'...所以是的,在那一刻它会* *为空。也许你想打印'att [i]'?你有没有在调试器中一步一步地执行这个步骤,并查看每一行的'token'? –
我在for循环中打印出att [1],但仍然给出了一个空值,但是我能够在for循环中打印出att [0] – JWalters
因此,使用调试器并查看'tokens'中的内容。 。 –