简体   繁体   English

在Android Studio中读取文件

[英]Read file in Android Studio

I'm trying simply read file in Custom View, but every time is my output Null. 我正在尝试只是在“自定义视图”中读取文件,但是每次都是输出Null。 There is my code: 有我的代码:

            try
            {
                    InputStream is = getResources().getAssets().open("text.txt");
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String st = "";
                    StringBuilder sb = new StringBuilder();
                    while ((st=br.readLine())!=null)
                    {
                            sb.append(st);
                    }

                    Log.d(TAG, "Text: " + st);
                    br.close();

            }catch (IOException e)
            {
                    Log.d(TAG, "Error: " + e);
            }

I have file "text.txt" with text in folder app/src/main/assets. 我在文件夹app / src / main / assets中有带有文本的文件“ text.txt”。 What am I doing wrong? 我究竟做错了什么?

problem is in line Log.d(TAG, "Text: " + st); 问题出在Log.d(TAG,“ Text:” + st);

you are printing the value of st which becomes null after loop completion as you describe in condition of while 您正在打印st的值,该值在循环完成后变为空,如您在while条件中所述

you are actually storing you result in Stringbuilder variable sb 您实际上将结果存储在Stringbuilder变量sb中

So print this variable 所以打印这个变量

Log.d(TAG, "Text: " + sb.toString); Log.d(TAG,“ Text:” + sb.toString);

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

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