简体   繁体   中英

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. 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.

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

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; try { 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()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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