gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:07:54 24 4
gpt4 key购买 nike

我和我的 friend 正在 Android Studio 中编写一个简单的应用程序。当您按下按钮时,将打开一个新 Activity ,其中包含您按下的按钮的名称,并显示该文件中的文本。

我有生成第一组按钮的代码(这些按钮是硬编码的),并且我可以获得按下的按钮的名称。我的麻烦是读取文本文件并显示内容。文本文件中的每一行都是一个单词,需要作为按钮的文本值。我无法对这些单词进行硬编码,因为它们经常会发生变化。

示例;在主要 Activity 中,您按下标有“Round”的按钮,它会将您发送到一个页面,该页面将名为“round”的文本文件中的所有单词列为按钮。

我之前问过这个问题,但由于太模糊而被搁置。我希望这更清楚。

这是我正在使用的代码,但需要代码来读取文件。这不能正常工作。

我什至无法让它显示第一行。文件内容是这样的——管道弯头 reducer 点击平面电子商务

请帮忙。提前致谢。

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

最佳答案

好吧,我找到了答案。感谢您为我指明了正确的方向。这是这里

    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);
}

关于java - 需要从android studio中的assets文件夹中读取txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34868261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com