0

目标:从文本文件中获取值并将其存储到值中以加载到我的 sqlite 数据库中。

问题:我的方法效率不高,我需要帮助想出一个更简单的方法。

截至目前,我正在解析我的文本文件,看起来像这样。

agency_id,agency_name,agency_url,agency_timezone,agency_lang,agency_phone
1,"NJ TRANSIT BUS","http://www.njtransit.com/",America/New_York,en,""
2,"NJ TRANSIT RAIL","http://www.njtransit.com/",America/New_York,en,""

每次读取逗号时我都会解析,然后将该值存储到一个变量中,然后我将使用该变量作为我的数据库值。

这种方法有效且耗时,我必须读入的下一个文本文件有超过 200 行代码,我需要找到一种更简单的方法。

AgencyString = readText();
        tv = (TextView) findViewById(R.id.letter);

        tv.setText(readText());

        StringTokenizer st = new StringTokenizer(AgencyString, ",");

        for (int i = 0; i < AgencyArray.length; i++) {
            size = i; // which value i am targeting in the textfile 
//ex. 1 would be agency_id, 2 would be agency_name
            AgencyArray[i] = st.nextToken();
        }
        tv.setText(AgencyArray[size]);  //the value im going to store into database value
    }

    private String readText() {
        InputStream inputStream = getResources().openRawResource(R.raw.agency);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int i;
        try {
            i = inputStream.read();
            while (i != -1) {
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toString();

    }
4

2 回答 2

1

First, why is this a problem? I don't mean to answer your question with a question so to speak, but more context is required to understand in what way you need to improve the efficiency of what you're doing. Is there a perceived delay in the application due to the parsing of the file, or do you have a more serious ANR problem due to you running on the UI thread? Unless there is some bottleneck in other code not shown, I honestly doubt you'd read and tokenise it faster that you're presently doing. Well, actually, no doubt you probably could; however, I believe it's more a case of designing your application so that delays involved in fetching and parsing of large data aren't perceived by or cause irritation to the user. My own application parses massive files like this and it does take a fraction of a second, but it doesn't present a problem due to the design of the overall application and UI. Also, have you used the profiler to see what's taking time? And also, have you run this on a real device, without debugger attached? Having the debugger attached to the real device, or using the simulator greatly increases execution time by several orders.

I am making the assumption that you need to parse this file type after receiving it over a network, as opposed to being something that is bundled with the application and only needs parsing once.

于 2012-08-17T19:41:23.133 回答
0

您可以将 SQLite 数据库与您的应用程序捆绑在一起,而不是在文本文件中表示它。看看这个问题的答案

于 2012-08-17T19:37:57.210 回答