簡體   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