简体   繁体   English

需要从android studio中assets文件夹中的txt文件中读取

[英]Need to read from a txt file in the assets folder in android studio

My buddy and I are writing a simple app in Android Studio.我和我的朋友正在 Android Studio 中编写一个简单的应用程序。 When you push a button, a new activity opens with the name of the button you pushed and displays the text in that file.当你按下一个按钮时,一个新的活动会以你按下的按钮的名称打开,并显示该文件中的文本。

I have the code that generates the first set of buttons (these are hard coded), and I can get the name of the buttons pushed.我有生成第一组按钮的代码(这些是硬编码的),我可以得到按下的按钮的名称。 My trouble is reading the text file and displaying the contents.我的麻烦是读取文本文件并显示内容。 Each line in the text file is a word that needs to be the text value of a button.文本文件中的每一行都是一个单词,需要是按钮的文本值。 I can't hard code the words because they can change often.我不能硬编码这些词,因为它们经常变化。

Example;例子; On the main activity you push the button labeled "Round", it sends you to a page that has all the words in the text file named "round" listed as buttons.在主要活动中,您按下标记为“Round”的按钮,它会将您转到一个页面,该页面将名为“round”的文本文件中的所有单词列为按钮。

I asked this question earlier, but it was put on hold as too vague.我之前问过这个问题,但因为太含糊而被搁置了。 I hope this is more clear.我希望这更清楚。

Here's the code I'm using, but need the code to read the file.这是我正在使用的代码,但需要代码来读取文件。 This is not working right.这不正常。

I can't get it to display even the first line.我什至无法让它显示第一行。 The file contents are this --- Pipe Elbow Reducer Tap on flat EC文件内容是这样的 --- Pipe Elbow Reducer Tap on flat EC

Please help.请帮忙。 Thanks in advance.提前致谢。

public class test extends Activity {
    int counter = 0;

    protected void onCreate(Bundle savedInstanceState) {
        counter = 0;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content);
        TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(getAssets().open("round.txt")));

            // do reading, usually loop until end of file reading
            String mLine;
            while ((mLine = reader.readLine()) != null) {

                for (int row = 0; row < 10; row++) {
                    TableRow tblRow = new TableRow(this);
                    tblRow.setPadding(5, 30, 5, 5);
                    table.addView(tblRow);
                    int NUM_COL = 3;

                    for (int col = 0; col != NUM_COL; col++) {
                        Button btn = new Button(this);
                        btn.setText(mLine);
                        tblRow.addView(btn);
                        NUM_COL++;

                    }
                }

            }
        } catch (IOException e) {
            //log the exception
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //log the exception
                }
            }
        }
    }
}

Here's an image of my structure:这是我的结构图:

这是我的结构图

Well I found the answer.好吧,我找到了答案。 Thank you for pointing me in the right direction.谢谢你给我指明了正确的方向。 Here it is这里是

    try {
        InputStream is = getAssets().open("round.txt");

        // We guarantee that the available method returns the total
        // size of the asset...  of course, this does mean that a single
        // asset can't be more than 2 gigs.
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String text = new String(buffer);

        // Finally stick the string into the text view.
        // Replace with whatever you need to have the text into.

        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(text);

    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

Reworked the code and this is the one that works.重新编写了代码,这是有效的代码。 BufferedReader reader; BufferedReader 阅读器; try { InputStream is = getAssets().open("round.txt");尝试 { InputStream is = getAssets().open("round.txt");

        reader = new BufferedReader(new InputStreamReader(is));

        // Finally stick the string into the text of the button.

        TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);

        String line = reader.readLine();
        int lineLength = (line.length());
        while (line != null){

            TableRow tblRow = new TableRow(this);
            tblRow.setPadding(5, 30, 5, 5);
            table.addView(tblRow);


            for (int col = 0; col < NUM_COL; col++) {
                Button btn = new Button(this);
                btn.setTextSize(14);

                btn.setText(line);
                tblRow.addView(btn);
                line = reader.readLine();
            }
        };

    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

}

Try this... add getResources()试试这个...添加getResources()

reader = new BufferedReader(
                new InputStreamReader(getResources().getAssets().open("round.txt")));

U can read from a file, line by line like this:你可以像这样逐行读取文件:

        String filename = "filename.txt";
        BufferedReader bufferedReader = null;    
        try {
            bufferedReader = new BufferedReader(new InputStreamReader
                    (this.getAssets().open(filename), StandardCharsets.UTF_8));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
              //add the lines in some arraylist if you want to set them.
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

In Kotlin , we can do as在 Kotlin 中,我们可以这样做

val string = requireContext().assets.open("round.txt").bufferedReader().use {
            it.readText()
        }

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

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