我制作了一个包含多行的txt文件。 我想在不同的textView中显示txt文件的每一行。 我唯一能做的就是显示txt文件的第一行。 也许还有其他方法如何显示SD卡文件中的文字?
我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getTxtLine(2, R.id.textView1, txt);
public void getTxtLine(int textLine, int resId, File txtFile){
try {
FileInputStream fIn = new FileInputStream(txtFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
// byte buffer into a string
text = new String(aBuffer);
TextView text1 = (TextView)findViewById(resId);
text1.setText(text);
}
} catch (Exception e) {
}
答案 0 :(得分:0)
//使用API查找SD卡的目录 // 不要硬编码“/ sdcard” File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
答案 1 :(得分:0)
我认为你应该在xml中定义一个ViewGroup,即LinearLayout,RelativeLayout,在代码中定义新的TextView。调用ViewGroup的addView。根据您的代码:
ViewGroup mGroup;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGroup = (ViewGroup)findViewById(R.id.group);
getTxtLine(2, R.id.textView1, txt);
}
public void getTxtLine(int textLine, int resId, File txtFile){
try {
FileInputStream fIn = new FileInputStream(txtFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
// byte buffer into a string
text = new String(aBuffer);
TextView tv = new TextView(this);
tv.setText(text);
mGroup.addView(tv);
}
} catch (Exception e) {
}
}