从java中的csv文件中读取

时间:2014-10-09 05:07:34

标签: java csv

大家好我是编程的新手,我正在尝试从csv文件中读取并在监视器上显示结果.csv文件包含国家名称,年份和每年的蜂窝数据统计数据。这是一个片段,因为该文件包含252个国家/地区,但决定放置2个国家/地区,但这里是该文件包含内容的简短摘要:

World Development Indicators
Number of countries,252
Country Name,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012
Aruba,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.029310471,0,0,2.138784453,3.605985937,3.98141538,6.16435217,13.48254011,16.50927821,57.05427692,65.05605558,72.10431377,99.64250268,103.3849507,108.1325002,112.2180618,119.2038996,126.2103374,129.72824,0,131.8565401
Andorra,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1.307211734,1.278625641,1.250259142,4.424155104,8.538444783,13.44671556,22.12730607,32.14530928,35.99902139,43.27794118,45.77115817,68.60251444,73.82494308,79.48487497,84.27763597,78.1171579,80.2836099,82.06181111,84.06818386,83.53432222,81.50204186

我已经创建了cellularData文件,并通过手动硬拷贝文件的详细信息并将其放入Test类来测试它,并且它有效。但现在我必须从csv文件中读取并能够使用我的cellularData文件执行相同的操作。提供了TestCSVReader,我将遵循TestReaderCSV对CSV类文件的要求。我在创建csv类时遇到了麻烦,因为我是编程和读取File IO的新手。对于我的csv类,它具有以下属性和方法:

属性:

名为“countryNames”的实例变量,String类型的一维数组,其中包含从CSV文件中读取的所有国家/地区的名称。

名为“yearLabels”的实例变量,类型为int的一维数组,用于保存从CSV文件中读取的年份编号。

名为“cellularDataTable”的实例变量,double类型的二维数组,其中行表示国家/地区,列表示特定年份的订阅数。

方法:

接收文件名的构造函数。         我们将使用它来创建一个新的File对象和Scanner对象。

使用扫描仪对象,使用“nextLine()”读取CSV文件一行。

“getCountryNames”方法返回“countryNames”

“getYearLabels”方法返回“yearLabels”

“getParsedTable”返回“cellularDataTable”

我必须忽略csv文件的第一行,其中读取“世界开发指标”。但请阅读“国家数量,252”。由于有252个国家,我必须将其解析为int。一次读取一行CSV文件,直到到达以“国家/地区名称”开头的行。这一行的格式是:             “国名,[年份],[年]”             其中[year]是一个整数,我们将用它作为一年的标签。             例如:             “国名,1960,1961,1962”

•    To Read the rest of the CSV file one line at a time.
        The format is:
        "[country name],[count1],[count2][count3]
         [country name],[count1],[count2][count3]

但有麻烦和如何开始。这是我的csv类文件的片段:

import java.io.*;
import java.util.Scanner;


public class CSVReader {
String countryNames;
String[] country;
int yearLabels;
int[] yearNum;
double cellularDataTable;
double[][] tables;
Scanner scan;

public CSVReader(String file) throws IOException
{
    File data = new File(file);
    throw new FileNotFoundException("File doest not exist");

    countryNames="";

}
public String getCountryNames()
{
    return countryNames;
}
public int getYearLabels()
{
    return yearLabels;
}
public double getParsedTable()
{
    return cellularDataTable;
}
}

TestCSVReader下面是我的CVS类测试文件,因为它也是我的CSV类文件的指南。

/**
*  Tests the CSVReader class, which reads input from a CSV file. Uses
*  the attributes stored in CSVReader object to fill the CellularData class.
*/
public class TestCSVReader {

/**
 * Includes test examples for class CSVReader.
 */
public static void main(String[] args) 
{   
    final String FILENAME = "data/cellular.csv";    // Directory path for Mac OS X
    //final String FILENAME = "data\cellular.csv";  // Directory path for Windows OS (i.e. Operating System)


    CSVReader parser = new CSVReader(FILENAME);

    String [] countryNames = parser.getCountryNames();
    int [] yearLabels = parser.getYearLabels();
    double [][] parsedTable = parser.getParsedTable();      

    CellularData datatable;
    int numRows = parsedTable.length;
    int numColumns = parser.getNumberOfYears();
    int startingYear = yearLabels[0];
    datatable = new CellularData(numRows, numColumns, startingYear);


    for (int countryIndex = 0; countryIndex < countryNames.length; countryIndex++)
    {
        double [] countryData = parsedTable[countryIndex];
        datatable.addCountry(countryNames[countryIndex], countryData);                  
    }


    System.out.printf(countryNames[0] + " (1960 to 2012): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod(countryNames[0],1960,2012));
    // the output is: Aruba (1960 to 2012): 1170.50 

    System.out.printf(countryNames[100] + " (1960 to 2012): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod(countryNames[100],1960,2012));
    // the output is: Hungary (1960 to 2012): 1246.58 

    System.out.printf(countryNames[200] + " (1960 to 2012): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod(countryNames[200],1960,2012));
    // the output is: Singapore (1960 to 2012): 1582.80
    }
 }

此处还有我创建的CellularData类文件:

public class CellularData {

private Object [][]array;
private int year;

public CellularData(int rows, int columns, int year)
{
    array = new Object[rows+1][columns+1];  //add +1 because initializes the header.
    array[0][0] = "Country";
    this.year = year;
    for(int i=1;i<=columns;i++)
    {
    array[0][i] = year++;   //increments the year
    }
}

public void addCountry(String country, double []num)
{
    for(int i=0;i<array.length;i++)
    {    
    if(array[i][0] == null)     //checks if the first row is empty
    {
        addCountry(country, num, i);  //inserts the data 
        break;
    }
    }
}
private void addCountry(String country, double []num, int row)
{
    array[row][0] = country;
    for(int j = 1;j<array[row].length;j++)
    {
        array[row][j] = num[j-1];
    }
}
public double getNumSubscriptionsInCountryForPeriod(String country, int sYear, int eYear)
{
     double sum = 0;

    for (int i = 1; i < array.length; i++) {

            if (country.equalsIgnoreCase((String) array[i][0])) { //matches with the parameters passed ignoring CAPS
                int start = 1 + sYear - year;   //first index position of the year
                int end = start + (eYear - sYear);  //end position of the year

                if (start >= 0 && end < array[i].length) {   //checks to see if index position is out of bounds

                    for (int k = start; k <= end; k++) {
                        // System.out.println(">> " + country + " adding " + array[i][k]);
                        sum += (Double) array[i][k];   //sum of the stats
                    }
                }
                else {
                    //returns Error messgae and -1
                    System.out.println("ERROR : requested year "+sYear+" from "+ country+" is less than starting year "+this.year);
                    sum = -1;
                    }
            }
            }
    return sum;
    }

public String toString()
{ //prints the array.
    for(Object []a: array)
    {
        for(Object k:a)
        {
            System.out.print(k + "\t");
        }
        System.out.println();
    }
    return " ";
    }

 }

这也是我为cellularData创建的测试文件,它只是从csv文件中复制和粘贴,但现在我需要从csv文件本身读取:

public class TestCellularData {

public static void main(String []args)
{
    final double[] usaPartial = {0,0,0.14,.28,.5,.83,1.39};
    final double[] canadaPartial = {0,0,.05,.23,.37,.75,1.26};
    final double[] mexicoPartial = {0,0,0,0,0,0,0.01};

     int numRows = 3;
     int numColumns = canadaPartial.length;
     int startingYear = 1983;

    CellularData datatable = new CellularData(numRows, numColumns, startingYear);
    datatable.addCountry("USA", usaPartial);
    datatable.addCountry("Mexico", mexicoPartial);
    datatable.addCountry("Canada", canadaPartial);

    System.out.println(datatable);

    System.out.printf("usa (1983 to 1989): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod("usa",1983,1989));
    // country is "usa", subscriptions from 1983 to 1989
    // the output is: 
    // usa (1983 to 1989): 3.14
    System.out.printf("mexico (1983 to 1989): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod("mexico",1983,1989));
    // country is "mexico", subscriptions from 1960 to 2000
    // the output is:
    // mexico (1983 to 1989): 0.01                  
    // NOTE: in order to get this result, you must test beyond the sample data included here and refer to the CSV file.
    System.out.printf("canada (1890 to 2000): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod("canada",1890, 2000));
    // the output is:
    // ERROR : requested year 1890  is less than starting year 1893
    // canada (1890 to 2000): -1.00 

     // Part 2
    System.out.println("\n\nPart 2 with All Data:");
    final double[] CANADA = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.046433382,
            0.229211886,0.370663166,0.752880479,1.264765577,2.110674786,2.769888481,3.621301434,
            4.648371087,6.435664704,8.840378661,11.82226558,14.04583637,17.73689555,22.72196984,
            28.42909462,34.36625958,37.94941948,42.07126881,47.06386648,52.75959279,57.49320536,
            61.47310755,66.20487722,70.54830532,75.676078,79.41215888,80.05046389};
    final double[] MEXICO = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
            0.001815204,0.010079818,0.074266061,0.183067275,0.348322481,0.421293924,
            0.608553991,0.721767371,1.051320868,1.758956617,3.326889843,7.556565917,
            13.55289414,20.65462731,24.29476815,27.85371761,35.15321825,42.56115672,
            49.40875353,58.62729509,65.49948112,71.45817512,77.51826326,79.24118294,83.35070827};
    final double[] USA = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.038253436,0.140659444,
            0.279060364,0.498659917,0.829863407,1.39281703,2.075802366,2.939643902,4.249049037,
            6.103716586,9.104921407,12.6047249,16.23815248,20.14238484,24.89063952,30.57610298,
            38.46809105,44.69057874,48.85103822,54.84681409,62.54719598,68.31769507,76.29353842,
            82.06414479,85.20916517,88.62364611,91.31165202,94.71891668,95.44786574};

    startingYear = 1960;
    numRows = 3;
    numColumns = CANADA.length;

    datatable = new CellularData(numRows, numColumns, startingYear);

    datatable.addCountry("canada", CANADA);
    datatable.addCountry("mexico", MEXICO);
    datatable.addCountry("usa", USA);

    System.out.println(datatable);

    System.out.printf("usa (1983 to 1989): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod("mexico",1983,1989));
    System.out.printf("mexico (1960 to 2000): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod("mexico",1960,2000));
    System.out.printf("canada (1890 to 2000): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod("canada",1890, 2000));

}
}

0 个答案:

没有答案