简体   繁体   English

Android:获取原始文件夹中文本文件的行数

[英]Android: Get number of lines of a text file in raw folder

Good day! 美好的一天! I've been trying create a function that will return the number of lines in a text file located at raw folder but I always seem to get 0. 我一直在尝试创建一个函数,它将返回位于raw文件夹的文本文件中的行数,但我似乎总是得到0。

Heres the function I am using: 继承我正在使用的功能:

int getFileSize (InputStreamReader p_is) { 
        int lineCtr = 0;
        try {
            BufferedReader br = new BufferedReader(p_is);

            String theLine="";
            lineCtr = 0;
            while ((theLine = br.readLine()) != null)   {
                lineCtr++;
            }
        } catch (Exception e) {
                e.printStackTrace();
        }
        return lineCtr;

    }

Then I pass variable size to another activity: 然后我将可变大小传递给另一个活动:

    InputStreamReader is = new InputStreamReader(getResources().openRawResource(R.raw.sampleTxt));          
    int size = getFileSize(InputStreamReader is);

    intent.putExtra("v_size", size);
    startActivity(intent);

Then I retrieve it in the other activity: 然后我在其他活动中检索它:

    fileSize = getIntent().getIntExtra("v_size",0);

When I try to show the fileSize, it always shows 0: 当我尝试显示fileSize时,它总是显示0:

    message= (TextView) findViewById(R.id.tv_message);

    String strSize = Integer.toString(fileSize);
    message.setText(strSize);

I have tried passing a string in putExtra() but it also shows 0. Please correct any mistakes you see and thank you for the help. 我已经尝试在putExtra()中传递一个字符串,但它也显示0.请更正您看到的任何错误,并感谢您的帮助。

It's your line 这是你的路线

int size = getFileSize(InputStreamReader is);

It doesn't need that InputStreamReader in there, that should show error when compiling code. 它不需要那个InputStreamReader ,它应该在编译代码时显示错误。 Not sure how you managed to run it. 不知道你是如何设法运行它的。

So you just have to remove that and then it should be able to read lines and the count you wanted. 所以你只需删除它,然后它应该能够读取你想要的行和计数。

Or is this getFileSize(InputStreamReader is) just a copy/paste error when you were writing your code to here? 或者,当您将代码写入此处时,此getFileSize(InputStreamReader is)只是一个复制/粘贴错误?

Try using this code: 尝试使用此代码:

public static int countLine(String s){
    int ct=0;
    for(int i=0;i<s.length();i++){
        if(s.charAt(i)=='\n')
            ct++;
    }
    return ct;
}

String s is result of reading text file, I tried this code, and it worked correctly 字符串s是读取文本文件的结果,我尝试了这段代码,并且它正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM