开发者

Character count from a text file

开发者 https://www.devze.com 2023-02-11 09:59 出处:网络
i am trying to count the number characters in a text file which i have retrieved the SD card need some advice here am 开发者_如何学Gonew to android programming

i am trying to count the number characters in a text file which i have retrieved the SD card need some advice here am 开发者_如何学Gonew to android programming

using this code to retrieve the text file from the sd card

        //Find the directory for the SD Card using the API
    //*Don't* hardcode "/sdcard"
    File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file
    File file = new File(sdcard,"file.txt");

    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }

    //Find the view by its id
    TextView tv = (TextView)findViewById(R.id.TextView01);

    //Set the text
    tv.setText(text);


Assuming that you have already opened the file and haven't encountered any exceptions in it, I would suggest using this, instead of what you're using:

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line="";
    int c,counter=0;
    while ((c = br.read()) != -1) {
        line+=(char)c;
        counter++;
    }
    text.append(line);
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

Here, I haven't used text.append("\n") because your file will already be having line break characters.

In the enc counter will be having the text count, including spaces and special characters like '\n'

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号