繁体   English   中英

Java-从csv文件读取获取空值

[英]Java - Reading from csv file getting null value

当我从老师那里读书时,我得到的是空值。 csv文件。 att [0]的列1有效,但是att [1]返回3个空值。

我的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***
            }

暂无
暂无

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

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