英文:
Android Studio - How to read (Line) from a text file?
问题
private ImageButton nextButton;
private TextView textView;
private int stringIndex = 0;
private ArrayList<String> dialog = new ArrayList<>();
private BufferedReader dialogReader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
textView = findViewById(R.id.textView);
nextButton = findViewById(R.id.imageButton);
// Load dialog from text file
try {
dialogReader = new BufferedReader(new InputStreamReader(getAssets().open("dialog.txt")));
String line;
while ((line = dialogReader.readLine()) != null) {
dialog.add(line);
}
dialogReader.close();
} catch (IOException e) {
e.printStackTrace();
}
textView.setText(dialog.get(stringIndex));
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
if (stringIndex == dialog.size() - 1) {
stringIndex = 0;
} else {
stringIndex++;
}
textView.setText(dialog.get(stringIndex));
}
});
}
Please make sure you have a text file named "dialog.txt" in the "assets" folder of your Android project, and each line of the file contains one dialog entry.
英文:
Right now my code looks like that:
private ImageButton nextButton;
private TextView textView;
private int stringIndex = 0;
private String[] dialog = {
"You: Hey, how are you?",
"She: I am fine and you?",
"You: I am fine as well!",
"She: Nice to meet you!"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
textView = findViewById(R.id.textView);
nextButton = findViewById(R.id.imageButton);
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
if (stringIndex == dialog.length-1){
stringIndex = 0;
textView.setText(dialog[stringIndex]);
} else {
textView.setText(dialog[++stringIndex]);
}
}
It works fine but what is bothering me is the String array. I prefer to save that dialog in a text file and read it line by line whenever I click on that button.
I saw some solution with assets and FileReader/BuffedReader but I am stucked and need your help!
答案1
得分: 0
这是一个关于FileInputStream、FileOutputStream和BufferedReader的很好的教程。易于理解的示例可以在以下链接找到:
https://www.androidauthority.com/lets-build-a-simple-text-editor-for-android-773774/
英文:
Here's a good tutorial about FileInputStream, FileOutputStream and BufferedReader. It's easy to understand the examples.
https://www.androidauthority.com/lets-build-a-simple-text-editor-for-android-773774/
专注分享java语言的经验与见解,让所有开发者获益!
评论