0

我在从我正在开发的 android 应用程序的 CSV 文件中提取值时遇到了一些问题。CSV 文件采用以下格式:

Acton Town (District),Acton Town (Piccadilly),2.00
Aldgate (Circle),Aldgate (Metropolitan),4.00
Aldgate East (District),Aldgate East (Hammersmith And City),2.00

我正在尝试使用以下方法将其导入我的 java 类:

public ArrayList<Connection> importConnections(){
        try 
        {
            //gets the lines.txt file from assets
            in = this.getAssets().open("connections.csv");
            Scanner scan = new Scanner(in);
            TextView lineData = (TextView)findViewById(R.id.displayLine);
            String connection = null;
            String startingStation = null;
            String endingStation = null;
            Float duration = 0;
            do
            {
                connection = scan.nextLine();
                String delimiter = ",\n";
                StringTokenizer tokens = new StringTokenizer(connection, delimiter);
                startingStation = tokens.nextToken();
                endingStation = tokens.nextToken();
                duration = Float.parseFloat(tokens.nextToken());
                connections.add(startStation, endStation, duration);
            }
            while(scan.hasNext());
            //for testing purposes
            lineData.setText(endingStation);
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return connections;
    }

如果我运行它,应用程序将崩溃,我不知道为什么。如果我设置lineData.setText(endingStation)lineData.setText(connection),它将显示整行,例如:

Acton Town (District),Acton Town (Piccadilly),2.00

如果我注释掉

持续时间 = Float.parseFloat(tokens.nextToken());

它将运行该方法。任何人都可以找到这种方法的任何错误吗?

4

1 回答 1

3

您可以尝试使用 OpenCSV http://opencsv.sourceforge.net/

它使用起来非常简单,并返回每行的数组。

CSVReader reader = new CSVReader(new FileReader(<filepath>));

String[] temp;
int NUM = #; //number of rows in csv, or insert code to read through file until null.

for(int i = 0; i < NUM; i++)
{               
    temp = reader.readNext();               //read next line into temp
}

System.out.println(temp[0]); //Acton Town (District)
System.out.println(temp[1]); //Acton Town (Piccadilly)
System.out.println(temp[2]); //2.00 (string)


reader.close();

就像我说的那样,它很容易使用,并且可以防止您不得不自己解析字符串。

于 2013-03-01T15:19:06.653 回答