读取CSV文件

时间:2016-10-20 22:19:50

标签: java csv

我只想阅读另一个名为“data.csv”的文件,并想知道我是否可以使用相同的布局来阅读ambulance.csv的内容?我正在尝试将两个内容的输出打印到控制台上。

data.csv的内容

id  x.location  y.location  status  ambulance
1       17          19      Assigned    A64
2       50          50     Completed    
3       78          29      Pending 
4       97          12     Pending  
5       27          17    Pending   
6       28          17    Pending   
7       67          2     Pending   
8       3           99    Pending   
9      30          81     Pending   
10     49           50    Pending   

ambulance.csv的内容

    id  x.location  y.location  status  patient
    A7       17        25   Responding   2
    A42      9         31   At Scene     1
    A117     1          1   At Station  

读取文件的代码

import java.awt.List;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


import javax.swing.JTable;

    public class AmbulanceSystem {

        public static void main(String[] args) {

            ArrayList<String[]> elements = new ArrayList<String[]>();

            String csvFile = "ambulances.csv";


            BufferedReader br = null;
             String line = "";
            String cvsSplitBy = ",";
            ArrayList<Patient[]> patients = new ArrayList<Patient[]>();
            ArrayList<Ambulance[]> ambulances = new ArrayList<Ambulance[]>();

            try {

                br = new BufferedReader(new FileReader(csvFile));
                while ((line = br.readLine()) != null) {

                    // use comma as separator
                    String[] location = line.split(cvsSplitBy);

                    System.out.println("(" + location[1] + " ," + location[2] + ")");

                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

        }

    }

我的输出

(x.location ,y.location)
(17 ,25)
(9 ,31)
(1 ,1)

0 个答案:

没有答案