Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中读取csv文件_Java_Csv - Fatal编程技术网

在java中读取csv文件

在java中读取csv文件,java,csv,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,197

大家好,我是编程新手,我正在尝试读取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文件,并通过手动硬拷贝该文件的详细信息并将其放入测试类中对其进行了测试,结果成功了。但是现在我必须从csv文件中读取数据,并且能够对cellularData文件执行相同的操作。提供了TestCSVReader,我将遵循TestReaderCSV对我的CSV类文件的要求。我在创建csv类时遇到了问题,因为我不熟悉编程和读取文件IO。对于我的csv类,它具有以下属性和方法:

属性:

名为“CountryName”的实例变量,是一个字符串类型的一维数组,它保存从CSV文件读取的所有国家的名称

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

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

方法:

接受文件名的构造函数。 我们将使用它来创建一个新的文件对象和扫描仪对象

使用Scanner对象,使用“nextLine()”读取CSV文件一行

“getCountryNames”方法,该方法返回“countryNames”

“getYearLabels”方法,该方法返回“yearLabels”

“getParsedTable”,返回“cellularDataTable”

我不得不忽略csv文件的第一行,其中的内容是“世界发展指标”。但改为“国家数量252”。由于有252个国家,我必须将其解析为int。每次读取一行CSV文件,直到到达以“国家名称”开头的行。该行的格式为: “国家名称,[年],[年]” 其中,[year]是一个整数,我们将使用它作为一年的标签。 例如: 国家名称,196019611962

但是有困难和如何开始。以下是我的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
    }
 }

使用一个合适的库,比如CSV,比你第一次想的要复杂得多……这个问题似乎离题了,因为OP没有对此做任何研究。直接发布SO以获得代码帮助。仅仅因为变量声明为
final
,并不意味着它是一个常量,应该用大写字母书写。有关详细信息,请阅读命名约定:
/**
*  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
    }
 }
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 " ";
    }

 }
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));

}
}